在SpringApplicationConfiguration中声明配置类的顺序。春季启动

时间:2016-06-14 09:28:05

标签: java spring spring-boot spring-test

我有这样的Spring Boot测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {
    PropertyConfig.class,
    ServiceConfigA.class,
    ServiceConfigB.class}
)
public class SpringTest {

    @Test
    public void test() {
    ...
    }
}

PropertyConfig类在类列表中首先声明时,我得到了上下文初始化错误,因为PropertyConfig中的bean被忽略,而来自服务配置的bean无法自动装配某些字段。当我在一些服务配置之后移动PropertyConfig时,PropertyConfig内的bean被初始化。

更详细地说,PropertyConfig包含两个bean:PropertiesFactoryBeanPropertySourcesPlaceholderConfigurerPropertySourcesPlaceholderConfigurer不存在的原因服务配置中的bean无法使用带有@Value注释的自动装配字段(无法自动从String转换为整数)。

我的问题是为什么来自PropertyConfig的bean在第一种情况下没有初始化? Spring Boot测试中是否有一些配置加载功能?

2 个答案:

答案 0 :(得分:0)

Spring扫描注册到CI容器中的依赖项,并计算出它们的初始化顺序。您所指的订单根本不相关。

如果它失败了,你的接线中还有其他一些问题。但是你没有告诉我们你的代码,很难说出根本原因。

答案 1 :(得分:0)

请参阅@Bean的Javadoc的“BeanFactoryPostProcessor-返回@Bean方法”部分:

  

必须特别考虑返回的@Bean方法   Spring BeanFactoryPostProcessor(BFPP)类型。因为BFPP对象   必须在容器生命周期的早期实例化,他们可以   干扰注释的处理,如@Autowired,@ Value,   和@Configuration类中的@PostConstruct。避免这些   生命周期问题,将BFPP标记为静态返回@Bean方法。对于   例如:

 @Bean
 public static PropertyPlaceholderConfigurer ppc() {
     // instantiate, configure and return ppc ...
 }
     

通过将此方法标记为静态,可以调用它而不会导致其声明@Configuration类的实例化,因此   避免上述生命周期冲突。但请注意   对于作用域和AOP,不会增强静态@Bean方法   语义如上所述。这可以在BFPP案例中得到解决   通常不会被其他@Bean方法引用。作为提醒,一个   将为任何非静态@Bean方法发出WARN级别的日志消息   具有可分配给BeanFactoryPostProcessor的返回类型。

换句话说,请确保您的PropertiesFactoryBeanPropertySourcesPlaceholderConfigurer bean被声明为static,并且它应该有效。