我有一个配置文件config.properties
,其中包含以下内容:
myFirstName='John'
myLastName='Doe'
我还有一个非常简单的配置类,它仅输出config.properties
文件的值:
@Configuration
@ComponentScan(basePackages = {"com.boot.Training.*"})
@PropertySource("classpath:config.properties")
public class AppConfig {
@Value("${myFirstName}")
private static String myFirstName;
@Value("${myLastName}")
private static String myLastName;
public static void showVariables() {
System.out.println("firstName: " + myFirstName);
System.out.println("lastName: " + myLastName);
}
}
问题是,即使这些值在config.properties
文件中显然已被赋予值,当它们输出到控制台时,它们仍显示为空。:
2018-09-08 10:52:46.334 INFO 2787 --- [ main] c.b.Training.EnvironmentVariables.App : Started App in 2.542 seconds (JVM running for 3.084)
firstName: null
lastName: null
我在这里想念什么?
答案 0 :(得分:2)
您的问题与static
关键字有关。因为静态字段初始化发生在 Spring容器启动之前的许多处理器周期中。因此,从您的类变量中删除关键字@Value("${myFirstName}")
private String myFirstName;
@Value("${myLastName}")
private String myLastName;
;
public class AppMain {
public static void main(String args[]){
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.close();
}
}
编辑: 我添加了可以正常工作的代码。我的主要班级就是这样开始春天的背景的。
AppConfig.class
所以在我的@Configuration
@ComponentScan(basePackages = "com.example.spring")
@PropertySource(value = {"classpath:application.properties"})
public class AppConfig implements InitializingBean {
@Value("${firstKey}")
private String myFirstName;
@Value("${secondKey}")
private String myLastName;
public void showVariables() {
System.out.println("firstName: " + myFirstName);
System.out.println("lastName: " + myLastName);
}
public void afterPropertiesSet() throws Exception {
showVariables();
}
}
中是这样的;
InitializingBean
不要在意实现application.configuration
。它提供了当创建bean时您想要什么。就像postConstruct一样。
我的firstKey = firsKeyValue
secondKey = secondKeyValue
是;
org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400: startup date [Sun Sep 09 11:37:35 EET 2018]; root of context hierarchy
firstName: firsKeyValue
lastName: secondKeyValue
现在,当我启动应用程序时,我看到此输出;
tab order
我认为它正在工作。应用您的要求并尝试一次。