你如何使用类中另一个类的bean?

时间:2013-11-05 14:54:30

标签: spring spring-java-config

使用xml,我能够定义一个常见的xml文件,我可以在其中放置用于其他不同condig文件的common bean。 我将我的配置移动到psring java config,如何使用java config实现这一点?

让我说我的公共课程为:

@Configuration
public class Common {
    @Bean
    public A a(){
        return new A();
    }
}

我希望将其用作

@Configuration
public class AConfig {

    @Bean
    public ABB abb(){
        ABB abb = new ABB();
        //TODO abb.set  ????
        return abb;
    }
}

缺少TODO部分,我想使用公共类中的a()。 这可能吗?

2 个答案:

答案 0 :(得分:2)

最简单的方法就是在这样的私人会员中“自动装配”:

@Configuration
public class AConfig {

    @Autowire
    private A myA;

    @Bean
    public ABB abb(){
        ABB abb = new ABB();
        abb.setA(myA);  // or MUCH better, make the A member of ABB private final and overload a construtor
        return abb;
    }
}

这样做的原因是AConfig也是一个Bean。它必须由Spring Bean Factory构建。施工结束后,将进行后期施工活动 - 其中一项是处理施工后注释,如Autowired。所以'myA'将在@Bean注释方法中使用之前设置。

答案 1 :(得分:1)

来自@Import注释Javadoc:

 * <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
 * Only supported for classes annotated with {@code @Configuration} or declaring at least
 * one {@link Bean @Bean} method, as well as {@link ImportSelector} and
 * {@link ImportBeanDefinitionRegistrar} implementations.
 *
 * <p>{@code @Bean} definitions declared in imported {@code @Configuration} classes
 * should be accessed by using {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
 * injection. Either the bean itself can be autowired, or the configuration class instance
 * declaring the bean can be autowired. The latter approach allows for explicit,
 * IDE-friendly navigation between {@code @Configuration} class methods.
 *
 * <p>May be declared at the class level or as a meta-annotation.
 *
 * <p>If XML or other non-{@code @Configuration} bean definition resources need to be
 * imported, use {@link ImportResource @ImportResource}

我假设如果您导入@Configuration类本身,即“后一种方法”,那么您只需在导入的类上显式调用@Bean方法,例如

@Configuration
@Import(BarConfiguration.class)
public class FooConfiguration {

    @Autowired
    private BarConfiguration barConfiguration;

    @Bean 
    public Foo foo() {
       Foo foo = new Foo();
       foo.setBar(barConfiguration.bar());
       return foo;
    }
}