我剛剛創建了一個spring mvc項目,除了web.xml
,spring-servlet.xml
和ListnerClass.java
之外沒有任何內容。
我想在服務器啓動過程中初始化系統屬性。爲此,我創建了一個servlet上下文從autowired bean獲取數據源時的空指針異常
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();
的web.xml
<?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>
爲spring-servlet.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>
不知道,但即使之前運行春天來生活上下文監聽器將被初始化。因此自動佈線可能不起作用。數據源實例不會自動初始化。你應該直接使用JNDI API來查找上下文初始化方法 –