前言:
今天刚好碰到了一个@Value 注解取不到值的问题 ,我们一起看一下,先看一下这个问题是怎么样的。
我写了一个工具类 ParameterParentUtil
@Value()注解一般用来取配置文件中的值,刚好我需要动态获取配置文件中的值。
package com.test.util;
import org.springframework.beans.factory.annotation.Value;
/**
* @Author tanghh
* @Date 2020/6/29 16:47
*/
public class ParameterParentUtil {
private static String code;
@Value("${spring.profiles.active}")
private static String environment;
public ParameterParentUtil(){
System.out.println("构造方法执行--------");
}
static{
System.out.println("static方法执行--------");
if(environment.equals("test")){
code = "100001";
}else{
code = "100002";
}
}
public static void getCode(){
System.out.println("code的值----"+code);
}
}
我们来执行一下上述代码。
package com.test.test;
import com.test.util.ParameterParentUtil;
/**
* @Author tanghh
* @Date 2020/6/29 16:54
*/
public class parameterTest {
public static void main(String[]args){
//1.获取code的参数值
ParameterParentUtil.getCode();
}
}
运行程序发现 报错了,是我的 environment 这个变量获取不到值。
报错原因:
1.@Value 需要通过依赖注入的方式进来,也就是说ParameterParentUtil 这个类需要加上@Service @Component 注解 就可以。
2.@Value 不能作用于静态变量(用static 修饰),不能作用于常量(final 修饰)
3.如果是在配置工具类获取值的话,可以通过另外一种方式也可以将值获取到。
接下来我来讲一下第三点的实现方式:
public static Object getParamentFromProperties(String key) {
InputStream is = ParameterParentUtil.class.getClassLoader().getResourceAsStream("application.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Properties props = new Properties();
try {
props.load(br);
return props.get(key);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
修改之后 ParameterParentUtil中的值:
package com.test.util;
import org.springframework.beans.factory.annotation.Value;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* @Author tanghh
* @Date 2020/6/29 16:47
*/
public class ParameterParentUtil {
private static String code;
// @Value("${spring.profiles.active}")
// private static String environment;
public ParameterParentUtil(){
System.out.println("构造方法执行--------");
}
static{
System.out.println("static方法执行--------");
String environment = (String) getParamentFromProperties("spring.profiles.active");
System.out.println(environment);
if(environment.equals("test")){
code = "100001";
}else{
code = "100002";
}
}
public static void getCode(){
System.out.println("code的值----"+code);
}
public static Object getParamentFromProperties(String key) {
InputStream is = ParameterParentUtil.class.getClassLoader().getResourceAsStream("application.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Properties props = new Properties();
try {
props.load(br);
return props.get(key);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
接下来我们运行一下程序 再测试一下这个功能,可以看到现在程序不报错了,问题已经解决。