How does autowiring work in Spring?

后端 未结 11 1601
执笔经年
执笔经年 2020-11-22 15:35

I\'m a little confused as to how the inversion of control (IoC) works in Spring.

Say I have a service class called UserServic

11条回答
  •  再見小時候
    2020-11-22 16:22

    There are 3 ways you can create an instance using @Autowired.

    1. @Autowired on Properties

    The annotation can be used directly on properties, therefore eliminating the need for getters and setters:

        @Component("userService")
        public class UserService {
    
            public String getName() {
                return "service name";
            }
        }
    
        @Component
        public class UserController {
    
            @Autowired
            UserService userService
    
        }
    

    In the above example, Spring looks for and injects userService when UserController is created.

    2. @Autowired on Setters

    The @Autowired annotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of userService when UserController is created:

    public class UserController {
    
        private UserService userService;
    
        @Autowired
        public void setUserService(UserService userService) {
                this.userService = userService;
        }
    }
    

    3. @Autowired on Constructors

    The @Autowired annotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of userService is injected as an argument to the constructor when UserController is created:

    public class UserController {
    
        private UserService userService;
    
        @Autowired
        public UserController(UserService userService) {
            this.userService= userService;
        }
    }
    

提交回复
热议问题