Spring在ServletContextAware bean中设置WebApplicationContext

我正在将现有代码转换为Spring 3 JDBC。我把它放到一个实现ServletContextAware的类(SpringDB.Users)中。在setServletContext()中,以下代码不起作用:
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,即当数据库工作真正开始时 - 所以我所做的是调用私有函数getSimpleJdbcTemplate()而不是私有变量simpleJdbcTemplate:
static private SimpleJdbcTemplate getSimpleJdbcTemplate ()
{
    if (simpleJdbcTemplate == null)
    {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        simpleJdbcTemplate = (SimpleJdbcTemplate) wac.getBean("simpleJdbcTemplate");
    }
    return simpleJdbcTemplate;
}
有没有解决方案,以便变量simpleJdbcTemplate可以在
setServletContext()
内初始化? 我错过了一些明显的东西,还是只是期待太多?     
已邀请:
你为什么一开始就需要这个? 如果你的类是bean,那么你可以简单地注入(使用
@Inject
@Autowired
或xml)jdbc模板:
@Inject
private SimpleJdbcTemplate template;
    

要回复问题请先登录注册