Spring study notes -- about the problem that Spring annotation scan cannot inject new objects
Over the past few days, Leader has made me use the factory model to refactor some of the business logic code. The process is painful (I will not elaborate on it here) and the results are very sweet. Below is a record of a problem I encountered during the refactoring process.
Some code is as follows:
@ Service (orderFactory) public class OrderFactory implements IOrderFactory {public OrderCreate factory (String type) {if (type! = Null & type. indexOf ("1 ")! =-1) {return new OrderOfType1 () ;}}@ servicepublic class OrderOfType1 {@ Autowired public OrderDao orderDao; // at this time, orderDao is empty and Spring is not injected}
After finding this problem, I first checked whether OrderOfType1 is in the Spring container, and then added the @ service custom alias. Using @ qualifier injection is ineffective. Suddenly I used the new keyword.
It turns out that after new is used, the OrderOfType1 class is not managed by Spring, and the annotation of Spring is to scan for injection during Spring instantiation, after the Spring instantiation is complete, if the new object is obviously not managed by Spring. You can use the following methods:
@service(orderFactory)public class OrderFactory implements IOrderFactory{ @Autowried private OrderOfType1 orderOfType1; public OrderCreate factory(String type){ if(type != null && type.indexOf("1")! = -1){ return orderOfType1(); } }}
Solve the problem after modification.