Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

annotation based factory methods

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?

like image 786
piotrek Avatar asked Feb 08 '13 19:02

piotrek


People also ask

What are factory methods in Spring?

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.

What is factory static method?

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.

What is the @bean annotation?

@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 .

What is static factory method in Spring?

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.


2 Answers

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();
    }

}
like image 107
Tomasz Nurkiewicz Avatar answered Sep 20 '22 18:09

Tomasz Nurkiewicz


You need java-config - the @Bean annotation.

Define your class as @Configuration and your method as @Bean

like image 24
Bozho Avatar answered Sep 21 '22 18:09

Bozho