对于spring static变量
下面给大家介绍spring不能注入static变量的原因,具体详情如下所示:
Spring 依赖注入是依赖 set方法
set方法是普通的对象方法
static变量是类的属性
只能在setAppId方法上加注解,另外class需要加 @Component等注解,这样spring才能扫描到
对于
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mysqk.db}") public static String DATABASE; }DATABASE的值是null
但是静态的XXX如何注入呢?
上网查了很多的说法,其实很简单:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import lombok.Getter; @Component public class GlobalValue { @Getter public static String DATABASE; @Value("${mysql.db:test}") public void setDatabase(String db) { DATABASE = db; } } DATABASE可以获取到值这里要特别注意,自动生成的getter和setter方法,会带有static的限定符,需要去掉,才可以。
然后通过bean获取
@PostConstruct方式实现
import org.mongodb.morphia.AdvancedDatastore; import org.springframework.beans.factory.annotation.Autowired; @Component public class MongoFileOperationUtil { @Autowired private static AdvancedDatastore dsForRW; private static MongoFileOperationUtil mongoFileOperationUtil; @PostConstruct public void init() { mongoFileOperationUtil = this; mongoFileOperationUtil.dsForRW = this.dsForRW; } }@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;(@PreDestroy 注解定义容器销毁之前的所做的操作) 这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作