The difference between the automatic assembly annotation @Autowired and @Resource in the interview article

Both can be automatically assembled, and their functions are similar, but there are still quite a few differences.


@Resource does not belong to Spring but supports it needs to be imported,

import jakarta.annotation.Resource;

And @Autowired comes with Spring

import org.springframework.beans.factory.annotation.Autowired;


@Autowired only uses type injection as follows,



By default it requires the object to exist, otherwise it throws an error. If null values ​​are allowed, you need to set his required to false. If we want to assemble by name, we need to use it with @Qualifier



@Resource is automatically assembled according to the name by default. It has two important attributes, name and type, which can be thought of according to the word. One by type and one by name. When neither is specified, name is used for automatic injection by default. The usage is as follows

 

Guess you like

Origin blog.csdn.net/weixin_69218754/article/details/130780001
Recommended