Spring 4 Create Bean Programmatically -


i've been looking way add datasources @ runtime. want move away defining datasources in @configuration class , instead when app loads want dynamically create datasource beans , inject them spring context. i'm not sure how can go doing that.

this ended with, not sure if right approach or not, if there better way please share.

    @component class springcontextlistener implements applicationlistener<contextrefreshedevent> {      public void onapplicationevent(contextrefreshedevent event) {         org.apache.tomcat.jdbc.pool.datasource ds = new org.apache.tomcat.jdbc.pool.datasource();         ds.setdriverclassname("com.mysql.jdbc.driver");         ds.seturl("jdbc:mysql://mysql:3306/test?useunicode=true&characterencoding=utf8&maxallowedpacket=512000");         ds.setusername("myusername");         ds.setpassword("mypassword");         configurableapplicationcontext ctx = (configurableapplicationcontext) event.getapplicationcontext();         configurablelistablebeanfactory bf = ctx.getbeanfactory();         bf.registersingleton("mysqldsn", ds);     }; } 

this example of want do, have ability dynamically create beans , add them them spring rather writing out config files.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -