【问题标题】:Order of declaring config classes in SpringApplicationConfiguration. Spring Boot在 SpringApplicationConfiguration 中声明配置类的顺序。弹簧靴
【发布时间】:2016-06-14 09:28:05
【问题描述】:

我有这样的 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 注释自动装配字段(无法自动从字符串转换为整数)。

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

【问题讨论】:

  • 我的提示是否让您的PropertySourcesPlaceholderConfigurer bean static 为您工作?

标签: java spring spring-boot spring-test


【解决方案1】:

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

如果它对您来说失败了,那么您的接线中肯定存在其他问题。但是你没有向我们展示你的代码,所以很难说出根本原因。

【讨论】:

    【解决方案2】:

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

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

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

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

    换句话说,确保您的 PropertiesFactoryBeanPropertySourcesPlaceholderConfigurer bean 被声明为 static,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 2018-02-14
      • 2017-12-21
      • 1970-01-01
      • 2019-05-03
      • 2018-07-10
      • 2021-04-20
      • 1970-01-01
      • 2023-01-07
      相关资源
      最近更新 更多