【发布时间】:2019-12-31 18:11:14
【问题描述】:
我有一个用于识别用户的 jsp 登录页面。为了配置 JdbcTemplate ,我在 "WEB-INF/applicationContext.xml" 下使用 spring 设置了它的属性,因此为了加载 spring 上下文,我在 web.xml 中添加了一些标签。但是,在 UserDao 类中自动装配 jdbcTemplate bean 会导致 NullPointerException!
applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="com.firstapp.dao"/>
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"></property>
</bean>
类 DAO
public class UserDAO
{
@Autowired
private JdbcTemplate jdbcTemplate;
....}
类服务
public class UserService
{
private UserDAO userDAO = new UserDAO ();
....}
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
【问题讨论】:
-
UserDAO 对象是通过 Spring 还是使用 new 运算符创建的? UserDAO 类是否使用任何 spring 注释进行注释?
-
@RamPrakash UserDAO 对象被一个新的操作符实例化
-
重复:
You cannot create Spring Bean objects directly through constructor. It's not the idea of dependency injection. Wherever you need your UserDAO, you need to autowire it, or else it won't work.
标签: java spring nullpointerexception web.xml jdbctemplate