java spring注入 静态方法_spring实现静态注入(类或者属性)

[spring实现静态注入(类或者属性)]()

场景是:工具类一般都是静态方法,静态方法只能访问静态属性。所以,我们需要静态注入类或者属性。

常规操作:

注入类或者方法:

@Autowired

private TestService testService;

@Resource

private TestService testService;

@Value("${key}")

private String key;

这样,我们就把容器里的类和Enviroment里的值注进去了。

静态注入操作:

我们使用相同的方式进行注入

@Autowired

private static TestService testService;

@Resource

private static TestService testService;

@Value("${key}")

private static String key;

我们在静态方法使用的时候,会出现null;

发现注入不进去。

解决办法有两种方式:

(1)@PostConstruct方式实现

@Component

public class TestUtil {

@Autowired

private static TestService testService;

private static TestUtil testUtils;

@PostConstruct

public void init() {

testUtils =this;

testUtils.testService =this.testService;

}

}

@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;(@PreDestroy 注解定义容器销毁之前的所做的操作)这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作;

(2)set方法注入实现

@Component

public class TestUtil {

private static TestService testService;

private static String key;

@Value("{key}")

public void setTestService(String key) {

TestUtil.key = key;

}

@Autowired

public void setTestService(TestService testService) {

TestUtil.testService =this.testService;

}

}

ok,完事,使用set方法注入,这种使用比较多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值