views:

270

answers:

4

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  A: 

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

Mark
+1  A: 
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");
Gandalf
I'm in the domain model, but it's kind of a service/domain sort of hybrid for my specific need. Is there any way to get the ServletContext without rippling it through my deep, deep, service layer?
Stefan Kendall
+1  A: 

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.

eugener
How do you do this?
Stefan Kendall
Although this doesn't really help, as the information changes when the domain object is moved to another server.
Stefan Kendall
Yes it does... When bean is "moved" to another server it is recreated there. As soon as it created it will be injected with another bean. Read about Spring and AOP
eugener
A: 

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.

Nate
That would be unnecessary network traffic. all the info is known on the server where domain object is
eugener
JNDI has nothing to do with the network... it's basically storing an object under a known name you can lookup on the server.
Nate
at least in this case :P
Nate
Here's an example of what I'm talking about - http://www.javapractices.com/topic/TopicAction.do?Id=127
Nate