温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot之@Value获取application.properties配置无效怎么解决

发布时间:2023-05-18 11:50:53 来源:亿速云 阅读:88 作者:iii 栏目:编程语言

今天小编给大家分享一下SpringBoot之@Value获取application.properties配置无效怎么解决的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

@Value获取application.properties配置无效问题

无效的原因主要是要注意@Value使用的注意事项:

  • 1、不能作用于静态变量(static);

  • 2、不能作用于常量(final);

  • 3、不能在非注册的类中使用(需使用@Componet、@Configuration等);

  • 4、使用有这个属性的类时,只能通过@Autowired的方式,用new的方式是不会自动注入这些配置的。

这些注意事项也是由它的原理决定的:

springboot启动过程中,有两个比较重要的过程,如下:

  • 1 、扫描,解析容器中的bean注册到beanFactory上去,就像是信息登记一样。

  • 2、 实例化、初始化这些扫描到的bean。

@Value的解析就是在第二个阶段。BeanPostProcessor定义了bean初始化前后用户可以对bean进行操作的接口方法,它的一个重要实现类AutowiredAnnotationBeanPostProcessor正如javadoc所说的那样,为bean中的@Autowired和@Value注解的注入功能提供支持。

下面说下两种方式:

resource.test.imageServer=http://image.everest.com

1、第一种

@Configuration
public class EverestConfig {
 
    @Value("${resource.test.imageServer}")
    private String imageServer;
 
    public String getImageServer() {
        return imageServer;
    }
 
}

2、第二种

@Component
@ConfigurationProperties(prefix = "resource.test")
public class TestUtil {
 
    public String imageServer;
 
    public String getImageServer() {
        return imageServer;
    }
 
    public void setImageServer(String imageServer) {
        this.imageServer = imageServer;
    }
}

然后在需要的地方注入就可

    @Autowired
    private TestUtil testUtil;
 
    @Autowired
    private EverestConfig everestConfig;
 
 
    @GetMapping("getImageServer")
    public String getImageServer() {
        return testUtil.getImageServer();
//        return everestConfig.getImageServer();
    }

@Value获取application.properties中的配置取值为Null

@Value("${spring.datasource.url}")

private String url;

获取值为NUll。

解决方法

不要使用new的方法去创建工具类(DBUtils)对象,而是使用@Autowired的方式交由springboot来管理,在工具类上加上@Component,定义的属性变量不要加static。

正确做法
@Autowired
private DBUtils jdbc;
  
@Component
public class DBUtils{
    
    @Value("${spring.datasource.url}")
    private String url;
}

以上就是“SpringBoot之@Value获取application.properties配置无效怎么解决”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI