网上有很多误导人的博文,在此亲测记录下。
下面介绍两种方法,要注意这两种方法必须在类上加@Component注解,这样Spring容器在加载时才会初始化相应注解下的方法。
1、 set注入法: private static boolean debug;//:false的意思是当gateway.request.log.debug不存在时默认为false,否则不存在会报错 @Value("${gateway.request.log.debug:false}") public void setDebug(boolean debug) { 类名.debug = debug; }Spring容器会在启动时执行@Value注解下的setDebug()方法。网上有人说必须是static 的set方法,坑人不浅,下面这种写法肯定是不行的(静态方法不会被容器加载时加载,只能在调用时设值)
private static boolean debug;//static方法不行@Value("${gateway.request.log.debug:false}")public static void setDebug(boolean debug) { 类名.debug = debug;} 2、@PostConstruct注解法:private static boolean debug; //临时变量 @Value("${gateway.request.log.debug:true}") private boolean debug_temp;@PostConstructpublic void init() { //把临时变量获取到的值设置到static变量中 类名.debug = debug_temp;}