Spring study notes -- about the problem that Spring annotation scan cannot inject new objects

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.