FactoryBeans and the annotation-based configuration in Spring 3.0

后端 未结 6 1685
-上瘾入骨i
-上瘾入骨i 2020-12-24 14:13

Spring provides the FactoryBean interface to allow non-trivial initialisation of beans. The framework provides many implementations of factory beans and -- when

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 14:39

    I think that this is best solved when you rely on auto-wiring. If you are using Java configuration for the beans, this would like:

    @Bean
    MyFactoryBean myFactory()
    { 
        // this is a spring FactoryBean for MyBean
        // i.e. something that implements FactoryBean
        return new MyFactoryBean();
    }
    
    @Bean
    MyOtherBean myOther(final MyBean myBean)
    {
        return new MyOtherBean(myBean);
    }
    

    So Spring will inject for us the MyBean instance returned by the myFactory().getObject() as it does with XML configuration.

    This should also work if you are using @Inject/@Autowire in your @Component/@Service etc classes.

提交回复
热议问题