Best way to manually pull a spring bean?

我的梦境 提交于 2019-12-10 12:05:47

问题


How do I pull a spring bean manually? I have a rather large web application, and in a given service, a transient object requires access to a bean that is machine specific (database connection info.) Since the application runs in a cluster, this transient object (which can bounce between servers) always needs to grab the correct connection been from the current spring context and server.

So, what's the best way to manually pull a bean out of spring?


回答1:


You could have your service implement ApplicationContextAware so that you have access to the ApplicationContext itself and can call getBean() directly on it.




回答2:


WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

Object o = ctx.getBean("dataSource");

Of course you can cast the bean like this:

DataSource d = (DataSource) ctx.getBean("dataSource");



回答3:


I would suggest injection of the object you trying to pull into your domain object "on creation". That means that whenever your domain object is created on specific server it will be injected with correct (machine specific) bean.




回答4:


It needs to get database connection info? How about storing the connection in JNDI and look it up in the bean? Assuming your server provides it.



来源:https://stackoverflow.com/questions/1262969/best-way-to-manually-pull-a-spring-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!