我正在使用 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.
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
我的客户 DAO …