aeb*_*bbl 7 java spring properties
问题:
当在类中使用@Conditional
bean 定义时,来自外部源的属性(例如文件)在评估时@Configuration
不可用-除非使用。无论使用哪个,使用代替都没有什么区别。Environment
Condition#matches
@PropertySource
ConfigurationCondition
Condition
ConfigurationPhase
由于我还要求对属性文件的名称使用通配符,因此@PropertySource
不能使用通配符,因为它要求位置是绝对的。Spring Boot 完全不可能,所以@ConditionalOnProperty
也不是一个选择。这让我将PropertySourcesPlaceholderConfigurer
bean 定义为唯一剩余的可行选择。
问题:
有没有什么方法可以根据使用普通 Spring 机制(不是启动,也不是其他一些黑客方式)中属性的存在、不存在或值来定义 bean,Environment
同时还使用通配符指定属性位置,如果是这样,需要什么完毕?
例子:
在下面的JUnit
测试中,我希望一个名为的 beanbean
可用,前提是该属性在 中的方法评估期间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;
}
}
}
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.properties
contains 的文件key=value
ConfigurationCondition
with ConfigurationPhase.REGISTER_BEAN
,只是为了表明它不会使行为变得更好 归档时间: |
|
查看次数: |
1544 次 |
最近记录: |