springboot如何使⽤@Value获取配置⽂件的值
使⽤@Value获取配置⽂件的值
1、创建配置⽂件(application.properties)
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.abled=false
2、创建测试类(MyController.java)
package ller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Value("${spring.activemq.user}")
private String user;
@RequestMapping("myTest")
public String myTest() {
System.out.println("user的值:" + user);
return "success";
}
}
3、打开浏览器访问 localhost:8080/myTest,控制台输出结果
SpringBoot 使⽤@Value()注解获取到配置⽂件中的值为null
⼀、描述
@Slf4j
@Component
public class FileUtils {
@Value("${document.path.output}")
private String outPath;
}
document:
path:
spring怎么读取配置output: E:/workspace/doc_convert/tmp
⼆、解决⽅式
新创建了⼀个SpringBoot项⽬,在使⽤@Value获取配置⽂件中的值时,⼀直为null。
通过排查发现,虽然值为null,说明配置的参地址是正确的,只是在Spring进⾏依赖注⼊的时候没有把这个值注⼊到变量中来。
通过检查发现,是由于使⽤此类(注解所在的类)时候是直接new的,并没有将此类的创建交由Spring容器进⾏管理。以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论