I want to be able to autowire a singleton bean (foo
)
@Component
public class FooUser {
@Autowire Foo foo;
}
created by another singleton's method (FooFactory.createFoo
)
@Service
public class FooFactory {
public Foo createFoo() {...}
}
with xml it's simply factory-method
. How can i do it with annotation?
Factory Method Types 1) A static factory method that returns instance of its own class. It is used in singleton design pattern. 2) A static factory method that returns instance of another class. It is used instance is not known and decided at runtime.
A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don't have a separate interface and implementation class.
@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .
Static factory methods are those that can return the same object type that implements them. Static factory methods are more flexible with the return types as they can also return subtypes and primitives too. Static factory methods are used to encapsulate the object creation process.
Try Java @Configuration
instead:
@Configuration
public class Config {
@Bean
public FooUser fooUser() {
return new FooUser(foo());
}
@Bean
public FooFactory fooFactory() {
return new FooFactory();
}
@Bean
public Foo foo() {
return fooFactory().createFoo();
}
}
You need java-config - the @Bean
annotation.
Define your class as @Configuration
and your method as @Bean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With