spring mvc在非Controller類無法使用Service bean解決方案
1、思路
因為不是在@Controller類中,使用@Autowired註解是得不到Service類的,所以可以通過手動方式進行獲取。
2、配置(如果已經配置好了,並且能在@Controller中獲得service類可以跳過這個)
為了更好的區分,所以spring mvc的xml配置進行了分層,每個目錄管理每個層次的東西,層次分明。
在web.xml檔案中配置srping的上線文。
在springmvc.xml中配置控制層的掃描
在applicationContext-service.xml中配置service的配置
配置好了的話在正常情況下使用@Controller、@RequestMapping進行說明,配合使用@Autowired註解說明這個service類,就可以獲得該類進行使用。
3、在非Controller類無法使用Service
由於不是在Controller類,所以使用@Autowired註解說明這個service類是沒有用的,無法獲取這個類,這個類還是null。
(1)首先在web.xml檔案中配置一個監聽,啟動的時候就執行這個監聽
<!-- 監聽(作用就是在非@Controller使用Service類首先需要實現該SpringInit類)-->
<listener>
<listener-class>
com.ssm.app.core.util.SpringInit
</listener-class >
</listener>
(2)SpringInit類(這個類的目的是獲取這個類的物件,為後續獲取Service做準備)
package com.ssm.app.core.util;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringInit implements ServletContextListener {
private static WebApplicationContext springContext;
public SpringInit() {
super();
}
public void contextInitialized(ServletContextEvent event) {
springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
}
public static ApplicationContext getApplicationContext() {
return springContext;
}
}
(3)假設我要在一個非Controller類中獲取service類
只需要在改類或需要呼叫該類的方法中加入這段程式碼:
AppCdService appcdService = (AppCdService)SpringInit.getApplicationContext().getBean("AppCdService");
解釋:
(1)AppCdService appcdService
是我需要的Service類,就相當@Autowired註解是需要的類,需要用我需要的類進行接收
(2)SpringInit.getApplicationContext().getBean(“AppCdService”)
SpringInit這個是監聽類的名稱,需要匯入這個類相關包,
getApplicationContext()是這個類的方法
getBean(“AppCdService”)是獲取Bean方法,其中AppCdService是applicationContext-service.xml中配置的中的id名稱,代表想取出那個Service進行註解。最後進行強轉為該Service。期間需要注意配置需要配對