方法一
目录结构
首先要编写application类,添加一些值
com:
ning:
value: hello
name: zhangsan
server:
servlet:
context-path: /yhj
port: 8888
接下来编写一个类,类中获取配置文件的值
package com.ning.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/boot")
public class Controller {
@Value("${com.ning.value}")
private String value;
@Value("${com.ning.name}")
private String name;
@GetMapping("getvalue")
public void firstConfInject(){
log.info("first conf inject: {},{}",value,name);
}
}
从浏览器上发送一个请求,这是控制台打印的日志成功获取到了配置文件的值
方法二
首先在pom文件中添加一个数据绑定的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
配置文件不变,编写一个类
package com.ning.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "com.ning")
public class ConfigGetValue {
private String value;
private String name;
}
这样,值就获取到了,验证方法是再写一个controller将这个类注入,再获取值