获取@Value配置文件的值 springboot怎样使用@Value获取配置文件的值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

获取@Value配置文件的值 springboot怎样使用@Value获取配置文件的值

知识追求者   2021-08-11 我要评论
想了解springboot怎样使用@Value获取配置文件的值的相关内容吗,知识追求者在本文为您仔细讲解获取@Value配置文件的值的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,boot配置文件,@Value配置文件的值,@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.activemq.pool.enabled=false

2、创建测试类(MyController.java)

package com.jeff.controller;
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、打开浏览器访问 http://localhost:8080/myTest,控制台输出结果

在这里插入图片描述

在这里插入图片描述

SpringBoot 使用@Value()注解获取到配置文件中的值为null

一、描述

@Slf4j
@Component
public class FileUtils { 
    @Value("${document.path.output}")
    private String outPath; 
}
document:
  path:
    output: E:/workspace/doc_convert/tmp

二、解决方式

新创建了一个SpringBoot项目,在使用@Value获取配置文件中的值时,一直为null。

通过排查发现,虽然值为null,说明配置的参地址是正确的,只是在Spring进行依赖注入的时候没有把这个值注入到变量中来。

通过检查发现,是由于使用此类(注解所在的类)时候是直接new的,并没有将此类的创建交由Spring容器进行管理。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们