Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...