我正在使用Spring DI,並試圖在我的servlet中注入Spring服務。但是,它沒有被注入並保持null
,導致NullPointerException
。沒有注入到web servlet中的Spring服務
我的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.
// ...
}
}
我的彈簧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;
// ...
}
我的彈簧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中注入'CustomerService' bean。我懷疑這是否正確。 –
我在不使用@Qualifier的情況下在我的servlet中注入bean,它不起作用 –
不要問爲什麼得到'NullPointerException'。 [每個Java開發人員都知道這個答案](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it)。相反,問爲什麼給定的變量是'空'。我從這個問題中減少了不相關的代碼,使它更好地集中。 – BalusC