我刚刚创建了一个spring mvc项目,里面除了web.xml
什么都没有, spring-servlet.xml
和ListnerClass.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();
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>
最佳答案
在部署描述符中注册的ServletContextListener
对象不是由Spring管理的,而是由Servlet容器管理的。因此,Spring 没有必要向其中注入(inject)任何 Bean。
经验法则是,如果您有一个 @Autowired
字段目标并且它是 null
,则 Spring 不参与其中。如果 Spring 无法解析 @Autowired
目标,它将抛出各种异常。
有解决方法:
关于java - 从 Autowiring bean 获取数据源时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954632/