I need to get prototype class from singleton. I found that method injection is the way to go, but I don't really know how to use spring @Lookup annotation.
I'm new to dependency-injection, and I chose to go with annotation configuration, so I would like to continue in that direction.
I found out that @Lookup annotation was added only recently (https://spring.io/blog/2014/09/04/spring-framework-4-1-ga-is-here), but I cannot find anywhere how to use it.
So, here is simplified example
Configuration class:
@Configuration
@Lazy
public class ApplicationConfiguration implements ApplicationConfigurationInterface {
@Bean
public MyClass1 myClass1() {
return new ContentHolderTabPaneController();
}
@Bean
@Scope("prototype")
public MyClass2 myClass2() {
return new SidebarQuickMenuController();
}
}
And here is class example:
public class MyClass1 {
doSomething() {
myClass2();
}
//I want this method to return MyClass2 prototype
public MyClass2 myClass2(){
}
}
How do I do that with @Lookup annotation?
Also, you can declare myClass2 bean with TARGET_CLASS proxyMode.
Before applying
@Lookup
annotation to yourpublic MyClass2 myClass2()
method, read this in @Lookup's Javadoc:So remove the following factory method style bean declaration from
ApplicationConfiguration
:and add
@Component
annotation to let Spring instantiate the bean (also add the@Lookup
annotation to the method):Now get
myClass1
bean out of context, and itsmyClass2
method should have been replaced/overridden to get a new prototype bean each time.Update:
Using factory method declaration
It's not hard to implement the
@Lookup
annotated method (the "lookup method"). Without@Lookup
and keeping your configuration class unchanged, nowMyClass1
looks like (in fact Spring generates a similar implementation in a subclass if@Lookup
were used):Spring injects the
ApplicationContext
for you.If you are not on Spring 4.1 you can use the provider injection instead:
This is DI, IoC, avoids abstract classes and xml definitions for lookup methods.