@Autowired @Resource
时间: 2023-10-05 18:15:09 浏览: 94
1.@Resource是按名称进行注入的,属于java自带的。@Autowired是按类型进行注入的,属于Spring。.pdf
@Autowired and @Resource are both annotations used in Spring Framework for dependency injection.
@Autowired is used to inject a bean by type. Spring will look for a bean of the same type as the field or parameter being annotated and automatically wire it to the class. If there are multiple beans of the same type, @Autowired can also be used with @Qualifier to specify which bean to inject.
@Resource is used to inject a bean by name. It can also be used to inject a bean by type, similar to @Autowired, but it requires a name attribute to specify the name of the bean to be injected. It is a standard Java EE annotation and can be used in non-Spring environments, but it is less flexible than @Autowired.
In general, @Autowired is recommended for most situations, as it is more flexible and can handle most injection scenarios. However, @Resource can be useful in certain cases where more fine-grained control over bean injection is needed.
阅读全文