一. 概念讲解
获取配置文件的注解方式有@value,@ConfigurationProperties
,这两种方式遇到下列情况都会失效:
① 属性前加上static
② 通过new 对象的方式调用属性
new Sm4Properties().getKey() // 这种方式调用
二. 正确方式
正确方法一
①给属性赋值
@Data
@Component
@ConfigurationProperties(prefix = "sm4")
public class Sm4Properties {
private String key;
}
sm4:
key: 2asjfo123jdfflk4
② 调用
通过实现 InitializingBean 接口,可以重写其带有的方法afterPropertiesSet(),这个方法作用是实现 InitializingBean 接口的类的属性赋值完成后,在进入到此方法中,当进入到此方法中,就可以获取到此key值,并将其赋值给此类的一个静态变量,这样就可以使用此静态变量了,也就相当于使用了yml配置文件中的值。
@Component
public final class JSONPut implements InitializingBean {
@Autowired
private Sm4Properties sm4Properties;
private static String key;
@Override
public void afterPropertiesSet() throws Exception {
key = sm4Properties.getKey();
}
正确方法二
给静态属性设置set方法,当然方法上不要加static
private static String url;
public static String getVoiceToTextUrl() {
return url;
}
@Value("${test.iflytekco.url:''}")
public void setVoiceToTextUrl(String url) {
(类名)IflytekVoice.url= url;
}
可能遇到的问题
问题一:@Value注入不进去
原因: @Value
所在位置不再springboot启动类所在文件夹,或其子文件夹下面,也就是没有被注解 @ComponentScan
注解扫描到,需要在启动类上添加上注解扫描, 注意:springboot默认扫描路径是启动类所在文件夹及其子文件夹,通过@ComponentScan注解实现,如果将此注解添加到启动类上默认的扫描路径就会失效,需要手动添加上,例 @ComponentScan(basePackages = {"test.ulane.ulink.*","baidu.video"})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)