@Autowired spring
时间: 2023-10-07 14:10:35 浏览: 91
Spring框架中 @Autowired 和 @Resource 注解的区别
5星 · 资源好评率100%
@Autowired is a Spring framework annotation used for automatic dependency injection. It is used to inject the dependent beans into the current bean's property or constructor. It helps to reduce the boilerplate code and improves the maintainability of the code.
When we use @Autowired annotation, Spring will automatically look for the bean that matches the required dependency and inject it into the current bean. We can use @Autowired annotation with constructor, setter or field injection.
For example, consider the following code snippet:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
// Other methods
}
```
In the above code snippet, we have used @Autowired annotation to inject the UserRepository bean into UserServiceImpl. Spring will automatically look for the UserRepository bean and inject it into the userRepository property of UserServiceImpl.
Note: To use @Autowired annotation, we need to enable component scanning in the Spring configuration file. We can do this by using @ComponentScan annotation or by configuring it in the XML configuration file.
阅读全文