当前位置:网站首页>@The difference between Autowired and @resource
@The difference between Autowired and @resource
2022-07-28 18:45:00 【web18224617243】
List of articles
One 、 Preface
@Autowired and @Resource Are used for automatic assembly bean Of .
- @Resource yes JSR-250 Provided , It is Java standard , Most frameworks support .
- @Autowired Very powerful , But only for Spring frame , If you change it to JFinal Etc , The function will fail .
Spring Bean Override configuration
spring:
main:
allow-bean-definition-overriding: true
allow-bean-definition-overriding Property is used to configure the occurrence of the same name bean How to deal with :
- The value is false when ( The default value is false), If the same name appears bean, Direct throw anomaly .
- The value is true when , Indicates that the same name is supported bean Cover , Later defined bean Will overwrite the previously defined with the same name bean.
Assembly by type... Will be mentioned below , So what is the same type ?
- Parent class And its Subclass , All belong to the type of parent class .
- Interface And its Implementation class , All belong to the type of interface .
Two 、@Autowired
@Autowired yes Spring Notes provided , For automatic assembly .
Annotation processor
AutowiredAnnotationBeanPostProcessor Class is Autowired Annotation processor for annotations .
For annotation processor, please refer to the article :https://blog.csdn.net/JokerLJG/article/details/123548694
Assembly method
- Assemble by type ( Assembly method used by default ).
- Assemble by name ( combination @Qualifier Annotations use ).
Annotation Properties
- required: The default value is true. The value is true when , Indicates that... Must be injected , Such as bean If it doesn't exist, it will report an error ; The value is false when , Express bean Exist and inject , If it does not exist, it will not be injected .
Scope of action
@Autowired The scope of action of : Member variables 、 Constructors 、 Method 、 Parameters 、 annotation .
1. Member variables
@Service
public class UserService {
@Autowired
private IUser user;
}
The most used way .
2. Constructors
@Service
public class UserService {
private IUser user;
@Autowired
public UserService(IUser user) {
this.user = user;
}
}
Use... On constructors Autowired annotation , In fact, the method of member variable assembly is used , It's not a constructor assembly .
3. Method
@Service
public class UserService {
@Autowired
public void test(IUser user) {
user.test();
}
}
Spring During the start of the project , Automatic call once added @Autowired Method of annotation , We can do some initialization work in this method .
4. Parameters
Add... To the input parameters of the constructor Autowired annotation
@Service
public class UserService {
private IUser user;
public UserService(@Autowired IUser user) {
this.user = user;
System.out.println("user:" + user);
}
}
Add... To the input parameters of non static methods Autowired annotation
@Service
public class UserService {
public void test(@Autowired IUser user) {
user.test();
}
}
5. annotation
A little .
Using skills
Multiple of the same type bean
When assembling by type , If this type of bean More than one time , Will report an error directly . Illustrate with examples :
Interface :
public interface IUser {
void test();
}
Implementation class 1:
@Service
public class User1 implements IUser{
@Override
public void test() {
}
}
Implementation class 2:
@Service
public class User2 implements IUser{
@Override
public void test() {
}
}
Automatic assembly :
@Service
public class UserService {
@Autowired
private IUser user;
}
Error message at startup :
Field userService in com.joker.controller.UserController required a single bean, but 2 were found:
- userServiceImpl1: defined in file [D:workmyspringboot argetclassescomjokercontrollerUserServiceImpl1.class]
- userServiceImpl2: defined in file [D:workmyspringboot argetclassescomjokercontrollerUserServiceImpl2.class]
@Primary Use
@Primary Annotations can solve the above problems ( When assembling by type , If this type of bean More than one time , Will report a mistake ).
When we use auto configuration to assemble Bean when , If this Bean There are multiple candidates , If one of the candidates has @Primary To modify , The candidate will be chosen , As an automatic assembly bean.
With the above code unchanged , Just in User1 or User2 add @Primary annotation , here @Autowired Automatic assembly will succeed , And the automatic assembly is added @Primary The annotated class corresponds to bean.
User1 Analogous addition @Primary annotation
@Service
@Primary
public class User1 implements IUser{
@Override
public void test() {
}
}
@Qualifier Use
adopt @Autowired and @Qualifier Can be assembled by name .
@Service
public class UserService {
@Autowired
@Qualifier("user1")
private IUser user;
}
The name of the automatic assembly is user1 Of bean( Be careful :bean The type of must also be IUser type ).
Assemble multiple instances
We usually use @Autowired Automatically assemble a single instance , But it can also be used to assemble multiple instances . Can pass List、Set、Map To assemble multiple instances , as follows :
@Service
public class UserService {
@Autowired
private List<IUser> userList;
@Autowired
private Set<IUser> userSet;
@Autowired
private Map<String, IUser> userMap;
}
The above assembly method will IUser Multiple instances of type bean All assembled List、Set、Map in .
@Autowired Assembly not effective
Here are some common @Autowired The assembly is not effective :
@Autowired The class does not add @Controller、@Service、@Component、@Repository Etc , Or some other situation ( Such as direct new Object to instance ). These conditions can lead to this kind of bean I didn't give it to you spring Containers to manage ,spring Can't complete the function of automatic assembly .
public class UserService { @Autowired private IUser user; public void test() { user.say(); } }The annotation was not modified @ComponentScan Scan to .
3、 ... and 、@Resource
@Resource yes JDK A self explanatory note , For automatic assembly .
Annotation processor
CommonAnnotationBeanPostProcessor Class is Resource The annotation processor .
Assembly method
@Resource Automatically inject by name by default .
It's not specified name, Not specified type, Automatically assemble by name ( When comments are written on fields , The default is the field name , When the annotation is written in setter When it comes to methods , By default, the attribute name is used for assembly .); If there is no match , Then retreat and assemble according to the type , Throw exception if not found .
If not specified name attribute ,
If you specify name, Find name from context (id) Matching bean Assembly , Throw exception if not found .
If you specify type, Then find the unique similar match from the context bean Assembly , Can't find or multiple , Will throw an exception .
If you also specify name and type, From Spring Unique match found in context bean Assembly , Throw exception if not found .
Annotation Properties
Resource The main attributes of annotations :
- name: Specify the... To be injected bean The name of
- type: Specify the... To be injected bean The type of
Scope of action
@Resource The scope of action of : class 、 Member variables 、 Method .
1. Member variables
@Service
public class UserService {
@Resource
private IUser user;
}
2. Method
@Service
public class UserService {
@Resource
public void test(IUser user) {
user.test();
}
}
3. class
A little .
Four 、@Autowired And @Resource contrast
distinguish between
@Autowired
@Resource
Spring Defined comments
JSR-250 Defined comments
Auto assemble by type by default
Auto assemble by name by default
One parameter :required( Default true), Indicates whether it is necessary to inject
Seven parameters : The two most important parameters are name、type
Auto assemble by type by default
If you want to assemble automatically by name , Need to use @Qualifier Work together
Auto assemble by name by default
If you specify name, Automatically assemble by name ; If you specify type, Automatically assemble by type
Scope of action : Constructors 、 Method 、 Parameters 、 Member variables 、 annotation
Scope of action : class 、 Member variables 、 Method
@Autowired Assembly process

@Resource Assembly process

边栏推荐
- MYSQL入门与进阶(十)
- UE5 GAS 学习笔记 1.9 技能系统全局类(AbilitySystemGlobals)
- 2022-07-27 study notes of group 4 self-cultivation class (every day)
- Golang并发模型之
- Go语言系列之日志库zap
- It is said that software testing is the worst in the IT industry. Is that so?
- MYSQL入门与进阶(七)
- Ue5 gas learning notes 8.0 references
- UE5 GAS 学习笔记 1.10 预测(Prediction)
- Calibration of vector network analyzer (vector network)
猜你喜欢

LeetCode_63_不同路径Ⅱ

LeetCode_96_不同的二叉搜索树

Introduction to oscilloscope

Calibration of vector network analyzer (vector network)

实验楼----PHP大法

Detailed explanation of network RJ45 interface

专题讲座6 树形dp 学习心得(长期更新)

APP为什么用JSON协议与服务端交互:序列化相关知识

Wired: who owns the art of the future? Openai allows dall-e users to commercialize their works. At present

MYSQL入门与进阶(四)
随机推荐
十进制转二进制进阶版(可转化负数以及边界值)
What is the employment prospect of software testing?
一文简述:SRv6基本原理
Ue5 gas learning notes 1.1 capability system component
Live broadcast starrocks technology insider: low base global dictionary optimization
Detailed explanation of oscilloscope probe
How to see the future development of software testing?
Ue5 gas learning notes 1.9 skill system global classes (abilitysystemglobals)
Ue5 gas learning notes 1.10 prediction
Golang并发模型之
2022.7.26 constructor, interview: the role of new, deep copy and shallow copy
MongoDB初始化
MongoDB数据库复制表
明德生物:公司暂未有产品被列入WHO推荐清单
Detailed explanation of oscilloscope parameters
Gateway入门
UE5 GAS 学习笔记 1.8 游戏特效(GameplayCue)
Bubble sorting and Related videos
Ue5 gas learning notes 0.1 case Preview
NPM cannot recognize the "NPM" item as the name of a cmdlet, function, script file, or runnable program. Please check the spelling of the name. If the path is included, make sure the path is correct,