背景說明
在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容器中代理類,注入到工具類靜態方法中,可根據個人習慣選擇使用