Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create annotation-configured beans with an existing instance of @Configuration?

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());
like image 604
lexicore Avatar asked Oct 15 '22 03:10

lexicore


1 Answers

It's impossible, because some features of Spring's @Configuration require class enhancement, that can't be done on the existing instance.

For example, you can rewrite your configuration as follows:

@Configuration 
public class FooBarConfiguration { 

    @Bean 
    public Foo createFoo() { 
        return new FooImpl(); 
    } 

    @Bean 
    public Bar createBar() { 
        return new BarImpl(createFoo()); 
    } 
} 

and you'll still get a fully initialized instance of Foo, because call to createFoo() will be intercepted.

like image 97
axtavt Avatar answered Oct 27 '22 00:10

axtavt