1. 程式人生 > >Spring-MVC @Autowired 注入成功幾次後就為null

Spring-MVC @Autowired 注入成功幾次後就為null

問題:如標題所說,程式中有一個Entity的類,使用了@Component 和 @Scope("prototype") 註解。Entity這種類對應的是資料庫的表,定是要多例。但在spring-mvc啟動的時候,實現無參建構函式,斷點發現只調用了兩次就不再呼叫。PS(在該Entity類上用了多少個@Autowired就呼叫了多少次)。多次呼叫Controller中方法後,entity居然注入為null。

解決方法:1.Entity 和 使用的Autowired注入的兩個類都是用@Scope("prototype") 進行註解,比如我的Controller類中有,那麼Controller類也得用@Scope("prototype"),每次請求也得重新建立Controller。Entity也就重新建立。

2.Spring建議Controller使用單利,這樣有助於提高效能。方法1雖能解決,但我建議使用動態直接獲取方法。即使用WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();

wac.getBean("xxxx");

敬上錯別字,收下!