我一直在打破这个问题.不确定我错过了什么.我无法@Value在纯java配置的spring应用程序(非web)中使用注释
@Configuration
@PropertySource("classpath:app.properties")
public class Config {
@Value("${my.prop}")
String name;
@Autowired
Environment env;
@Bean(name = "myBean", initMethod = "print")
public MyBean getMyBean(){
MyBean myBean = new MyBean();
myBean.setName(name);
System.out.println(env.getProperty("my.prop"));
return myBean;
}
}
Run Code Online (Sandbox Code Playgroud)
属性文件只包含my.prop=avaluebean如下:
public class MyBean {
String name;
public void print() {
System.out.println("Name: " + name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
环境变量正确打印值,而@Value不是.
avalue
Name: ${my.prop}
主类只是初始化上下文.
AnnotationConfigApplicationContext ctx = …Run Code Online (Sandbox Code Playgroud) 我有一个Spring @Configuration类,它应该在环境中设置特定属性值时注册bean.我编写了一个自定义Condition实现,检查该值是否存在,并且当我在Spring Boot中启动应用程序时它可以工作,但是在运行JUnit测试时从未注册过bean.我调试了应用程序并确定在实例化Condition之前正在评估PropertySourcesPlaceholderConfigurer它.
我修改了我Condition的实现ConfigurationCondition并在REGISTER_BEAN阶段中指定了评估.在实例化configurer之前仍然调用该方法,但是当我从属性文件中添加或删除属性时,已注册的bean现在来去.
这是重新评估评估的最佳方式吗?这是ConfigurationCondition接口的用途,还是我现在不小心让它上班?
@Conditional(PropertyCondition.class)
@Configuration
public class PostbackUrlConfiguration {
@Value("${serviceName.postbackUrl}")
String postbackUrl;
@Bean
public PostbackUrlProvider provider() {
return new FixedUrlProvider(postbackUrl);
}
}
Run Code Online (Sandbox Code Playgroud)
public class PropertyCondition implements ConfigurationCondition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().containsProperty("serviceName.postbackUrl");
}
@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}
}
Run Code Online (Sandbox Code Playgroud)
测试配置是我测试用例的静态类:
@Configuration
@ComponentScan
@PropertySource("classpath:/postback.properties")
@Import(PostbackUrlConfiguration.class)
public static class TestConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer …Run Code Online (Sandbox Code Playgroud) Spring 4有两个新的注释@Condition,@ConfigurationConditon用于控制是否将bean添加到spring应用程序上下文中.JavaDoc没有提供足够的上下文/大图来理解用例@ConfigurationCondition.
什么时候应该@ConfigurationCondition用@Condition?
public interface ConfigurationCondition extends Condition {
/**
* Returns the {@link ConfigurationPhase} in which the condition should be evaluated.
*/
ConfigurationPhase getConfigurationPhase();
/**
* The various configuration phases where the condition could be evaluated.
*/
public static enum ConfigurationPhase {
/**
* The {@link Condition} should be evaluated as a {@code @Configuration} class is
* being parsed.
*
* <p>If the condition does not match at this …Run Code Online (Sandbox Code Playgroud)