我將現有代碼轉換爲Spring 3 JDBC。我把它放到一個實現ServletContextAware的類(SpringDB.Users)中。在setServletContext(),下面的代碼無法正常工作:Spring設置ServletContextAware bean中的WebApplicationContext
public void setServletContext(ServletContext sc)
{
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
simpleJdbcTemplate = (SimpleJdbcTemplate) wac.getBean("simpleJdbcTemplate");
}
的原因是:例外的是java.lang.IllegalStateException:沒有找到的WebApplicationContext:沒有註冊ContextLoaderListener的?
但是我沒有註冊web.xml中的ContextLoaderListener:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
applicationContext.xml文件有這樣的:
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/mysql"/>
<bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg>
<ref bean="dataSource"/>
</constructor-arg>
</bean>
<bean class="SpringDB.Users"/>
導致越來越調用setServletContext()。 SpringDB.Users類大多是靜態的東西。它永遠不會被java代碼實例化。
顯然,對WebApplicationContextUtils.getRequiredWebApplicationContext()的調用「太早」。因爲什麼不工作,沒有任何麻煩的是在以後的時間來獲得WebApplicationContext中,即當數據庫的工作真正開始 - 所以我要做的就是打電話,而不是私有變量了SimpleJdbcTemplate私有函數getSimpleJdbcTemplate():
static private SimpleJdbcTemplate getSimpleJdbcTemplate()
{
if (simpleJdbcTemplate == null)
{
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
simpleJdbcTemplate = (SimpleJdbcTemplate) wac.getBean("simpleJdbcTemplate");
}
return simpleJdbcTemplate;
}
有沒有解決方案,以便變量simpleJdbcTemplate可以在setServletContext()
內初始化?
我錯過了一些明顯的東西,或者只是期待太多?
不編譯,因爲「非靜態變量模板不能從內引用一個靜態的上下文「。正如我所說的,這個類永遠不會被實例化。作爲靜態變量,「靜態字段不支持」Autowired註釋「。我知道我可以通過簡單地在調用bean中做一個getBean()來解決問題,但我試圖不改變數據庫bean之外的代碼。 – 2011-03-05 21:12:59
@Tilman Hausherr當然 - 擺脫所有靜態環境。你爲什麼需要它? – Bozho 2011-03-05 21:15:25
因爲我試圖不改變數據庫bean之外的現有代碼。該代碼從不實例化數據庫類,它只是使用靜態調用,這些類甚至沒有任何變量。是的,你的建議可以在一個非靜態變量的類中工作。我意識到,靜態調用通常是一個禁止按照「清潔代碼」的教學,但我試圖改進現有的代碼緩慢。(更多在下一個評論) – 2011-03-05 22:12:00