Junior — Middle
How to distinguish between using @Autowired and @Inject annotations in the Spring context and how do they differ?
sobes.tech AI
Answer from AI
The @Autowired (from Spring) and @Inject (from the JSR-330 standard) annotations are used for dependency injection in Spring applications.
Main differences:
- @Autowired is a Spring-specific annotation that supports additional features, such as the 'required' parameter to specify whether the dependency is mandatory.
- @Inject is a standard annotation from javax.inject, more universal and portable across different DI containers.
In Spring, they work very similarly, and @Autowired supports more configurations, but @Inject is preferred if compatibility with other frameworks is needed.
Example of using @Autowired:
@Autowired
private UserService userService;
Example with @Inject:
@Inject
private UserService userService;