在springBoot项目中,我们一般把参数配置到application.yml中,但是如果想在工具类的静态方法中使用这些参数,常用的三种方式:@value 、@ConfigurationProperties或 Environment 都没法取到值。
因此需要使用@PostConstruct 注解来实现
1、在application.yml中加入以下配置
server:
port: 10091
servlet:
context-path: /spring-boot-demo
read:
type:
T1: first
T2: second
T3: third
2、创建一个工具类 PropertiesUtil.java
package com.demo.springbootdemo.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @program: spring-boot-demo
* @author: MingYi
* @date: 2021/7/15 17:59
* @description: 属性文件获取
**/
@Component
public class PropertiesUtil {
@Autowired
private Environment environment;
private static Environment env;
//PostConstruct注解不可以有参数的
@PostConstruct
public void init(){
env = this.environment;
}
public static String getType(String id){
String key = "read.type.T"+id;
String type = env.getProperty(key);
return type;
}
}
3、在Controller或是其他地方直接使用此工具类即可:UtilController.java
package com.demo.springbootdemo.controller;
import com.demo.springbootdemo.util.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @program: spring-boot-demo
* @author: MingYi
* @date: 2021/7/15 19:50
* @description: 验证类
**/
@Slf4j
@RestController
public class UtilController {
@PostMapping("/test/getType")
public void getType(@RequestBody Map<String,String> reqMap){
String id = reqMap.get("id");
log.info("获取的类型:{}", PropertiesUtil.getType(id));
}
}
注意点:
1、这个解决方案的核心是@PostConstruct ,如果出现以下错误: java.lang.IllegalStateException: Lifecycle method annotation requires a no-arg method
这是因为使用此注解的方法 不可以有参数
2、使用@value @ConfigurationProperties 也是相同的思路