java - Spring 4 @Conditional:环境属性不可用,除非使用@PropertySource
问题描述
问题:
在类中使用@Conditional
bean 定义时,来自外部源(例如文件)的属性在评估时@Configuration
不可用-除非使用。无论使用哪个,使用代替都没有区别。Environment
Condition#matches
@PropertySource
ConfigurationCondition
Condition
ConfigurationPhase
由于我还需要对属性文件的名称使用通配符,因此使用@PropertySource
不是一种选择,因为它要求位置是绝对的。Spring Boot 完全不在桌面上,因此@ConditionalOnProperty
也不是一个选择。这让我将PropertySourcesPlaceholderConfigurer
bean 定义为唯一剩余的可行选项。
问题:
有没有办法根据Environment
使用普通 Spring 机制(不是引导,而不是其他一些 hacky 方式)中的属性的存在、不存在或值来定义 bean,同时还使用通配符指定属性位置,如果是这样,需要什么完毕?
例子:
在下面的测试中JUnit
,我希望一个名为的 bean可用bean
,如果在. 情况并非如此,因此测试失败。key
null
Environment
matches
PropertyCondition
@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;
}
}
}
一旦我像这样添加@PropertySource
注释ConditionTestConfiguration
:
@Configuration
@PropertySource("classpath:test.properties")
static class ConditionTestConfiguration
该属性key
可用,因此该PropertyCondition#matches
方法的计算结果为 true,因此bean
在 中可用ApplicationContext
并且测试通过。
附加信息:
test.properties
类路径中key=value
存在一个名为 contains 的文件- 我使用了
ConfigurationCondition
withConfigurationPhase.REGISTER_BEAN
,只是为了表明它不会更好地改变行为 - 为简洁起见,省略了包声明和导入语句
解决方案
推荐阅读
- javascript - 我可以在反应中以编程方式将道具传递给子组件吗?
- cytoscape.js - 多个背景图像相互叠加
- typescript - 在 map 语句中使用属性值作为键,无需中间对象分配
- c - 两个和问题中if语句的不同输出带有括号
- java - 如何以json格式将对象作为post请求的主体传递
- python - 使用 METIS 获取连接的分区
- python - 解析多个.html文件并删除部分html代码的方法
- tensorflow - 使用 Tensorflow 对象检测 API 在 Faster R-CNN 中可视化来自 RPN 头部的提议区域
- onvif - Onvif TranslationSpaceFov 平移空间是否需要通过转换 x,y 坐标来使相机视图居中
- javascript - PowerBI JS SDK - setFilters() 从过滤器面板中删除除第一个过滤器之外的所有过滤器