0

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?

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406

4 Answers4

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");
Gandalf
  • 9,648
  • 8
  • 53
  • 88
  • 1
    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 Aug 12 '09 at 00:10
1

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

Mark
  • 28,783
  • 8
  • 63
  • 92
1

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.

Eugene Ryzhikov
  • 17,131
  • 3
  • 38
  • 60
  • Although this doesn't really help, as the information changes when the domain object is moved to another server. – Stefan Kendall Aug 12 '09 at 17:18
  • 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 – Eugene Ryzhikov Aug 12 '09 at 17:35
0

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
  • 16,748
  • 5
  • 45
  • 59
  • That would be unnecessary network traffic. all the info is known on the server where domain object is – Eugene Ryzhikov Aug 12 '09 at 00:40
  • 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 Aug 12 '09 at 02:33
  • Here's an example of what I'm talking about - http://www.javapractices.com/topic/TopicAction.do?Id=127 – Nate Aug 12 '09 at 02:42