How does autowiring work in Spring?

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

    Depends on whether you want the annotations route or the bean XML definition route.

    Say you had the beans defined in your applicationContext.xml:

    
    
        
    
        
    
    
    

    The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImpl class, you'd annotate it as follows:

    public class FooController {
    
        // You could also annotate the setUserService method instead of this
        @Autowired
        private UserService userService;
    
        // rest of class goes here
    }
    

    When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than one UserService bean, then you'll have to qualify which one it should use.

    If you do the following:

    UserService service = new UserServiceImpl();
    

    It will not pick up the @Autowired unless you set it yourself.

提交回复
热议问题