天天看点

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

最近用@PropertySource直接加载配置文件,一开始想直接加载yml,但发现他只支持properties,于是写了一个properties

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

先只取其中一个format的值

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

可以看到我在构造器里面打印了format的值,然后想着在启动类里面直接new一个对象,这样就可以打印出值了

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

然后得到的结果却让我很失望(请忽略掉我没有打冒号分割)

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

我觉得一定是我那里配置错了,各种修改取值的方式,注解等等,都没有解决。然而容器中已经加载进了配置文件的内容:

request.getattribute取不到值_Spring Boot中@Value取不到值的问题

最后才发现,通过@PropertySource,配置文件被注入到Spring容器中,而自己new一个对象并不经过Spring容器,当然取不到值。AlipayService类上加了Component注解,所以正确的写法是,通过Autowired引入bean,然后获取属性值。

request.getattribute取不到值_Spring Boot中@Value取不到值的问题
request.getattribute取不到值_Spring Boot中@Value取不到值的问题

钻了个牛角尖,执着于构造器中的打印没有值,引用了bean却没有用bean获取属性值。

果然,跳出问题本身,往往会有不一样的发现。