views:

47

answers:

4

I have a Spring bean (singleton scope if it matters), lets call it FooService.

And I have an object Bar which is not managed by Spring but it want to use FooService.

How to implement this cooperation in the best way? (Let's assume that I don't like the solution with applicationContext.getBean()).

+1  A: 

Call "new" in your Bar constructor and create an instance of FooService for it to use.

duffymo
FooService is supposed to be a singleton (it's stateless, I don't need multiple instances).
Roman
@Roman - can't you just use the Singleton pattern then?
Noel M
@Roman - whatever. Just have a child reference in your Bar object and assign the appropriate reference to FooService.
duffymo
A: 

A Spring bean is ideally a Plain Old Java Object, or a POJO. If it's not Spring managed, then you'll have to manage it yourself. Ideally calling new, or something like a getInstance method, and then tracking the reference yourself.

Noel M
A: 

Who is constructing the Bar instance? You didn't mention this.

If a Bar instance requires a FooService, then you have to inject the latter into Bar with either constructor or setter injection.

If you want FooService to be managed by Spring, but not Bar, then you really only have a few options:

  1. In the code that constructs the Bar instance, pass it a reference to the FooService from your applicationContext
  2. Just as simple - use Spring to manage the lifecycle of a Bar instance as well.
matt b
+1  A: 

AOP is an option if you want dependency injection in objects that are not created by an IoC container. Take a look at Spring's @Configurable - I'd paste a link to a Stack Overflow question on the topic, but my cut-n-paste is currently broken.

hbunny
See: http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable
Pablojim