How does autowiring work in Spring?

后端 未结 11 1568
执笔经年
执笔经年 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:02

    Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:

    UserService userService = new UserServiceImpl();
    

    You will be using this after introducing DI:

    @Autowired
    private UserService userService;
    

    For achieving this you need to create a bean of your service in your ServiceConfiguration file. After that you need to import that ServiceConfiguration class to your WebApplicationConfiguration class so that you can autowire that bean into your Controller like this:

    public class AccController {
    
        @Autowired
        private UserService userService;
    } 
    

    You can find a java configuration based POC here example.

提交回复
热议问题