Assume we have a simple @Configuration
:
@Configuration
public class FooBarConfiguration {
@Bean
public Foo createFoo() {
return new FooImpl();
}
@Bean
@Autowired
public Bar createBar(Foo foo) {
return new BarImpl(foo);
}
}
This class can be used with AnnotationConfigApplicationContext
to produce Foo
and Bar
instances:
final ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(FooBarConfiguration.class);
final Foo foo = applicationContext.getBean(Foo.class);
final Bar bar = applicationContext.getBean(Bar.class);
assertSame(foo, bar.getFoo());
In the example above Spring will create a new instance of FooBarConfiguration
and use it to produce Foos and Bars.
Now assume we already have an instance of FooBarConfiguration
and we want to create Foos and Bars through Spring with this very instance. Is there a way to accomplish this?
How to create annotation-configured beans with an existing instance of configuration object?
ps. With Google Guice the solution is trivial:
public class FooBarConfiguration implements Module {
@Provides
@Singleton
public Foo createFoo() {
return new FooImpl();
}
@Override
public void configure(Binder binder) {
}
@Provides
@Inject
@Singleton
public Bar createBar(Foo foo) {
return new BarImpl(foo);
}
}
final FooBarConfiguration fooBarConfiguration = ...; // Our instance
final Injector injector = Guice.createInjector(fooBarConfiguration);
final Foo foo = injector.getInstance(Foo.class);
final Bar bar = injector.getInstance(Bar.class);
assertSame(foo, bar.getFoo());