[英]Failed to set value with application.properties
I'm trying a very simple code to inject a value from application.properties. 我正在尝试一个非常简单的代码来从application.properties中注入一个值。 The value which is setted is the property name.
设置的值是属性名称。
What's wrong with the code? 代码有什么问题?
application.properties application.properties
set.browser = ie
public class A {
@Value("${set.browser}")
private String browser;
public A(){}
public void print(){
System.out.println(browser);
}
}
@Configuration
public class ABean {
@Bean
public A getA(){
return new A();
}
}
public class AMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A.class);
A a = context.getBean(A.class);
a.print();
}
}
First of all your application is not spring boot application - you've just instanted spring context even without component scan. 首先,您的应用程序不是Spring启动应用程序 - 即使没有组件扫描,您也只是实例化了弹簧上下文。 Secondly beacause of lack of component scan, your ABean is never created - your context has only A bean.
其次,由于缺少组件扫描,您的ABean永远不会被创建 - 您的上下文只有一个bean。 To fix this you can create context from ABean:
要解决此问题,您可以从ABean创建上下文:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ABean.class);
Thirdly you didn't configured PropertySource (if your application was spring boot application, application.properties would be default property source and it wouldn't be needed): 第三,您没有配置PropertySource(如果您的应用程序是spring boot应用程序,则application.properties将是默认属性源,并且不需要它):
@PropertySource("classpath:/application.properties")
@Configuration
class ABean {
@Bean
public A getA() {
return new A();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.