spring mvc 工具類的靜態方法使用注入
阿新 • • 發佈:2018-12-30
類程式碼
@Component
public class RegisterConfig {
@Autowired
private DepartMentService departMentService;
public void setDepartMentService(DepartMentService departMentService) {
this.departMentService = departMentService;
}
private static RegisterConfig registerConfig;
@PostConstruct
public void init(){
registerConfig = this;
registerConfig.departMentService = this.departMentService;
}
public static String RootPath = System.getProperty("register.webapp");
public static int DepartMentIDLength(){
if(departMentIDLength == 0){
departMentIDLength = registerConfig.departMentService.departMentUnitIDLength();
}
return departMentIDLength;
}
private static int departMentIDLength = 0;
其中:@Component, @PostConstruct 還有private static RegisterConfig registerConfig;是關鍵,原理應該是容器啟動時例項化了RegisterConfig ,注入了departMentService,呼叫了init(),並將RegisterConfig.registerConfig初始化,然後就可以使用了。
因application.xml中的xml配置為 default-lazy-init=”true” ,所以要在這個配置檔案中加入一個配置,讓RegisterConfig 可以在容器啟動時就注入。
<beans>
<bean id="registerConfig" class="com.register.normalClass.RegisterConfig" init-method="init"
lazy-init="false">
</bean>
</beans>```
注:
這樣處理後是可以注入了,但是這個類中的一個讀取根目錄的變數卻讀取不到了,System.getProperty讀到的是null
public static String RootPath = System.getProperty("register.webapp");
這就需要在啟動監聽裡設定一下這個值:
//RegisterConfig加了靜態注入後,這個值就取不到了,所有在這個地方給他賦值
RegisterConfig.RootPath = System.getProperty("register.webapp");
如果哪位有更好的方法,請在評論裡給一下,謝謝