spring boot中如果需要从配置文件读取属性值,需要下面两部
- 首先在类上添加 @Component注解
- 然后在属性上加@Value("${paramValue}")。
但是,如果属性是静态的话,这总方法是行不通的,属性会是一个空值,那就需要一张变通的方法,通过set方法注入,代码如下:
public static int ParamValue;
@Value("${paramValue}")
public void setParamValue(int value) {
ParamValue = value;
}
这样,就能获取到了,但是如果使用的这个类静态属性的是一个静态方法呢?有需要怎么呢。
我们都知道,静态方法的读取容器中的对象是会返回空的,除非我们通过applicationContext.getBean()来获取。通过这个思路我们可以通过下面3步来实现静态方法中读取静态属性。
1.和以前的思路一样,创建一个通过applicationContext获得对象的静态工厂方法,如下
package com.cmxf.utils;
import org.springframework.context.ConfigurableApplicationContext;
public class BeanUtil {
//将管理上下文的applicationContext设置成静态变量,供全局调用
public static ConfigurableApplicationContext applicationContext;
//定义一个获取已经实例化bean的方法
public static <T> T getBean(Class<T> c){
return applicationContext.getBean(c);
}
}
2.在spirngboot的启动类中,将applicationContext赋值给BeanUtil这个工具类中的applicationContext,代码如下:
package com.cmxf;
import com.cmxf.utils.BeanUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication()
public class DemoApplication {
public static void main(String[] args) {
//run方法的返回值ConfigurableApplicationContext继承了ApplicationContext上下文接口
ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
//将run方法的返回值赋值给工具类中的静态变量
BeanUtil.applicationContext = applicationContext;
}
}
3.然后就可以直接在静态方法中调用获得这个静态属性的值了,当然,这个方法也适用于费静态属性值的获取,代码如下:
public static String sayHello() {
StaticClassTest conf = BeanUtil.getBean(StaticClassTest.class);
return "Hello, "+conf.ParamValue;
}