I\'m a little confused as to how the inversion of control (IoC
) works in Spring
.
Say I have a service class called UserServic
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.