2

使用 xml,我能够定义一个通用 xml 文件,我可以在其中放置用于其他不同 condig 文件的通用 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() 。那可能吗?

4

2 回答 2

4

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

@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 注释方法中使用之前设置。

于 2014-03-06T19:19:54.070 回答
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;
    }
}
于 2014-03-06T19:05:41.533 回答