问题
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