Spring 4 @Conditional:除非使用@PropertySource,否则环境属性不可用

aeb*_*bbl 7 java spring properties

问题:

当在类中使用@Conditionalbean 定义时,来自外部源的属性(例如文件)在评估时@Configuration不可用-除非使用。无论使用哪个,使用代替都没有什么区别。EnvironmentCondition#matches @PropertySourceConfigurationConditionConditionConfigurationPhase

由于我还要求对属性文件的名称使用通配符,因此@PropertySource不能使用通配符,因为它要求位置是绝对的。Spring Boot 完全不可能,所以@ConditionalOnProperty也不是一个选择。这让我将PropertySourcesPlaceholderConfigurerbean 定义为唯一剩余的可行选择。

问题:

有没有什么方法可以根据使用普通 Spring 机制(不是启动,也不是其他一些黑客方式)中属性的存在、不存在或值来定义 bean,Environment同时还使用通配符指定属性位置,如果是这样,需要什么完毕?

例子:

在下面的JUnit测试中,我希望一个名为的 beanbean可用,前提是该属性在 中的方法评估期间key可用(即不可用null)。事实并非如此,因此测试失败。EnvironmentmatchesPropertyCondition

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ConditionTest.ConditionTestConfiguration.class })
public class ConditionTest {

  private static final String PROPERTIES_LOCATION = "test.properties";
  private static final String BEAN_NAME = "bean";

  @Autowired
  private ApplicationContext applicationContext;

  @Test
  public void testBeanNotNull() {
    assertNotNull(applicationContext.getBean(BEAN_NAME));
  }

  @Configuration
  static class ConditionTestConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
      propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource(PROPERTIES_LOCATION));
      return propertySourcesPlaceholderConfigurer;
    }

    @Bean
    @Conditional(PropertyCondition.class)
    public Object bean() {
      return BEAN_NAME;
    }

  }

  static class PropertyCondition implements ConfigurationCondition {

    private static final String PROPERTY_KEY = "key";

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
      return context.getEnvironment().getProperty(PROPERTY_KEY) != null;
    }

    @Override
    public ConfigurationPhase getConfigurationPhase() {
      return ConfigurationPhase.REGISTER_BEAN;
    }

  }

}
Run Code Online (Sandbox Code Playgroud)

一旦我添加@PropertySource注释,如下所示ConditionTestConfiguration

  @Configuration
  @PropertySource("classpath:test.properties")
  static class ConditionTestConfiguration 
Run Code Online (Sandbox Code Playgroud)

该属性key可用,因此该PropertyCondition#matches方法评估为 true,因此在测试bean中可用。ApplicationContext

附加信息:

  • 类路径中存在名为test.propertiescontains 的文件key=value
  • 我使用了ConfigurationConditionwith ConfigurationPhase.REGISTER_BEAN,只是为了表明它不会使行为变得更好
  • 为了简洁起见,省略了包声明和导入语句