【发布时间】:2016-05-17 06:06:13
【问题描述】:
我正在使用 Spring DI 并尝试在我的 servlet 中注入 Spring 服务。但是,它没有被注入并停留在null,导致NullPointerException。
我的小服务程序:
@WebServlet(urlPatterns = {"/Register"}, displayName = "RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Autowired
@Qualifier("registerServlet")
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
customerService.save(customer); // Fail, because service is null.
// ...
}
}
我的 spring-controller.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="registerServlet" class="com.fishingstore.controller.RegisterServlet">
<property name="customerService" ref="customerService"/>
</bean>
</beans>
我的客户 DAO 类:
@Repository
@Transactional
public class CustomerDAOImpl implements CustomerDAO {
private SessionFactory sessionFactory;
@Autowired
@Qualifier("sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// ...
}
我的客户服务类:
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
@Qualifier("customerService")
private CustomerDAO customerDAO;
// ...
}
我的 spring-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customerService" class="com.fishingstore.service.implementation.CustomerServiceImpl">
<property name="customerDAO" ref="customerDAO"/>
</bean>
</beans>
我的错误在哪里?
【问题讨论】:
-
您正在使用
registerServlet限定符在您的servlet 中注入CustomerServicebean。我怀疑这是正确的。 -
我在没有 @Qualifier 的情况下在我的 servlet 中注入 bean,它不起作用
-
不要问你为什么得到
NullPointerException。 Every Java developer knows the answer to that。而是询问为什么给定变量是null。我从问题中减少了不相关的代码,使其更加集中。 -
BalusC,谢谢,你是对的,我错误地提出了我的问题。我会更加专心。
标签: spring servlets dependency-injection