因为spring加载静态方法比IOC早,所以不能直接使用@Value注解读取yml配置,读取结果往往是null。
解决方式1我们可以通过@PostConstruct在服务加载Servlet的时候运行
@Configuration
public class DemoConfig {
//给静态变量赋值
@Value("${mvc.test}")
public int test;
public void setTest(int test) {
this.test = test;
}
public static int TEST;
@PostConstruct
public void init(){
DemoConfig.TEST = test;
}
}
然后在我们需要的地方调用就行了
@Component
public class MyConfig {
public void show(){
System.out.println(DemoConfig.TEST);
}
}
解决方式2
我们可以通过@AutoConfigureAfter 来在当前类注入到容器之前去加载相关配置类
@Configuration
public class DemoConfig {
public static int test;
//给静态变量赋值
@Value("${mvc.test}")
public void setTest(int test) {
DemoConfig.test = test;
}
}
@AutoConfigureAfter({DemoConfig.class}) //加载当前文件之前先去加载DemoConfig文件
@Component
public class MyConfig {
public void show(){
//然后在我们需要的地方调用就行了
System.out.println(DemoConfig.test);
}
}



