背景说明
在spring MVC 的项目中定义配置读取工具类时,发现需要使用Spring IOC容器进行注入,原始方法就是直接使用@Autowired 将依赖类注入到工具类中,想要用工具类时也得需要借助@Autowired进行注入,操作起来太复杂,完全丧失了工具类的灵活性。
下面整理了将Spring IOS容器中的对象注入到工具类静态方法中的三种实现方式,详细方式如下所示:
1、基于@PostConstruct 实现代码,详细代码如下所示:
//服务
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
public String get(String key){
return "OK";
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class ConfigUtil {
private static ConfigService configService;
//IOC注入
@Autowired
@Qualifier("configService")
ConfigService iocConfigService;
//初始化赋值
@PostConstruct
public void init() {
this.configService = iocConfigService;
}
//静态方法
public static String get(String key){
return configService.get(key);
}
}
2、基于set方法实现代码,详细代码如下所示:
//配置服务
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
public String get(String key){
return "OK";
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ConfigUtil {
//注入服务
private static ConfigService configService;
//服务赋值
@Autowired
public void setConfigService(ConfigService configService) {
ConfigUtil.configService = configService;
}
//静态方法
public static String get(String key){
return configService.get(key);
}
}
注:此Set方法之上需加上 @Autowired 注解
3、基于default-autowire="byName" 实现代码,详细代码如下所示:
//配置服务
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
public String get(String key){
return "OK";
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ConfigUtil {
private static ConfigService configService;
//赋值服务方法
public void setConfigService(ConfigService configService) {
ConfigUtil.configService = configService;
}
//获取服务方法
public static String get(String key){
return configService.get(key);
}
}
注:此种方法中需要使用 @Autowired 注解,但是需要在spring 的配置xml 中加上default-autowire="byName" 配置,详细代码如下所示:
<!--spring.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
" default-autowire="byName">
//...........
//...........
</beans>
以上代码均可实现将spring IOC容器中代理类,注入到工具类静态方法中,可根据个人习惯选择使用