从autowired bean获取数据源时出现空指针异常

时间:2014-01-06 16:34:09

标签: java spring spring-mvc autowired

我刚创建了一个spring mvc项目,除了web.xmlspring-servlet.xmlListnerClass.java之外,其中没有任何内容。
我想在服务器启动期间初始化系统属性。为此,我创建了一个servlet上下文

public class ListnerClass implements ServletContextListener{

    @Autowired
    private DataSource dataSource;

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {

        /* code for initializing system properties */
    Connection conn=dataSource.getConnection();

}

我在此行NullPointerExceptin Connection conn=dataSource.getConnection();获得了<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-servlet.xml </param-value> </context-param> <listener> <listener-class>com.infocentercache.manager.ListnerClass</listener-class> </listener> </webapp> 的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"    value="jdbc:mysql://localhost:3306/infocenter" />
        <property name="username"   value="root" />
        <property name="password" value="gaurav" />
    </bean>
</beans>

弹簧servlet.xml中

{{1}}

1 个答案:

答案 0 :(得分:3)

部署描述符中注册的ServletContextListener对象不由Spring管理,它由Servlet容器管理。因此,Spring没有业务注入任何bean。

经验法则是,如果你有一个@Autowired字段目标且它是null,那么Spring就没有参与其中。如果无法解析@Autowired目标,Spring将抛出各种异常。

有解决方法:

相关问题