I am using Spring DI and trying to inject a Spring service in my servlet. However, it isn't injected and stays null
, causing NullPointerException
.
My servlet:
@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.
// ...
}
}
My 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>
My Customer DAO class:
@Repository
@Transactional
public class CustomerDAOImpl implements CustomerDAO {
private SessionFactory sessionFactory;
@Autowired
@Qualifier("sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// ...
}
My Customer service class:
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
@Qualifier("customerService")
private CustomerDAO customerDAO;
// ...
}
My 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>
Where is my mistake?