当前位置:网站首页>@The difference between Autowired, @qualifier, @resource
@The difference between Autowired, @qualifier, @resource
2022-07-03 03:29:00 【ywl470812087】
Refer to the post :
http://www.cnblogs.com/happyyang/articles/3553687.html
http://blog.csdn.net/revent/article/details/49203619
http://blog.csdn.net/ad921012/article/details/49679745
spring Not only support your own definition @Autowired annotation , It also supports several JSR-250 A note on the definition of the specification , They are @Resource、@PostConstruct as well as @PreDestroy.
@Resource Is equivalent to @Autowired, It's just @Autowired Press byType Automatic injection , and @Resource Press default byName It's just automatic injection [email protected] There are two attributes that are important , Cent is name and type,Spring take @Resource Annotated name Property resolved to bean Name , and type Property resolves to bean The type of . So if you use name attribute , Then use byName Automatic injection strategy of , While using type Property is used byType Automatic injection strategy . If you don't specify name It doesn't specify type attribute , This will be used by the reflection mechanism byName Automatic injection strategy .
@Resource Assembly sequence
1. If you also specify name and type, From Spring Unique match found in context bean Assembly , Throw exception if not found
2. If you specify name, Find name from context (id) Matching bean Assembly , Throw exception if not found
3. If you specify type, Then find the unique type match from the context bean Assembly , Can't find or find more than one , Will throw an exception
4. If neither name, It's not specified type, Then automatically follow the byName Method of assembly ; If there is no match , Back off to match as an original type , Auto assemble if match ;
@Autowired And @Resource The difference between :
1、 @Autowired And @Resource Can be used to assemble bean. All can be written on the fields , Or in setter On the way .
2、 @Autowired Assembly by type by default ( This note is industry spring Of ), By default, dependency objects must exist , If you want to allow null value , You can set its required The attribute is false, Such as :@Autowired(required=false) , If we want to use name assembly, we can combine @Qualifier Use annotations , as follows :
1 2 |
|
3、@Resource( This note belongs to J2EE Of ), By default, assemble by name , The name can be given by name Property to specify , If not specified name attribute , When comments are written on fields , By default, the field name is used to search the installation name , If the note is written in setter Method, the property name is used for assembly by default . When no match can be found for the name bean Assembly according to type . But here's the thing , If name Property once specified , Just assemble by name .
1 2 |
|
Recommended :@Resource Comments on fields , So there's no need to write setter The method , And this annotation belongs to J2EE Of , Less with spring The coupling of . This makes the code look more elegant .
@Autowired It is automatically assembled according to the type . If so Spring More than one in context UserDao Type of bean when , Will throw BeanCreationException abnormal ; If Spring There is no... In the context UserDao Type of bean, It will also be thrown out BeanCreationException abnormal . We can use @Qualifier coordination @Autowired To solve these problems . as follows :
① There could be multiple UserDao example
perhaps@Autowired @Qualifier("userServiceImpl") public IUserService userService;@Autowired public void setUserDao(@Qualifier("userDao") UserDao userDao) { this.userDao = userDao; }
such Spring Will find id by userServiceImpl and userDao Of bean Assembly .
② May not exist UserDao example
@Autowired(required = false)
public IUserService userService Personal summary :
@Autowired// Press default type Inject
@Qualifier("cusInfoService")// As a general @Autowired() To modify with
@Resource(name="cusInfoService")// Press default name Inject , Can pass name and type Attribute for selective injection
commonly @Autowired and @Qualifier Together with ,@Resource Alone with .
Of course, if there is no conflict @Autowired It can also be used alone
----------- Commonly used annotations --------
-- Definition Bean Annotations
@Controller
@Controller("Bean The name of ")
Define the control layer Bean, Such as Action
@Service
@Service("Bean The name of ")
Define the business layer Bean
@Repository
@Repository("Bean The name of ")
Definition DAO layer Bean
@Component
Definition Bean, Use when it is difficult to classify .
-- Automatic assembly Bean ( Just choose an annotation )
@Autowired (Srping Provided )
Match by type by default , Automatic assembly (Srping Provided ), It can be written on member properties , Or in setter On the way
@Autowired(required=true)
Be sure to find a match Bean, Otherwise, throw it out of order . The default value is true
@Autowired
@Qualifier("bean Name ")
Assemble by name Bean, And @Autowired Use a combination of , Solve matching by type and find multiple Bean problem .
@Resource JSR-250 Provided
By default, assemble by name , When no matching name is found bean Then assemble according to the type .
It can be written on member properties , Or in setter On the way
Can pass @Resource(name="beanName") Specifies the injected bean The name of , If not specified name attribute , The variable name of the member attribute is used by default , Don't usually write name attribute .
@Resource(name="beanName") It specifies name attribute , Injected by name but not found bean, No more assembly by type .
@Inject yes JSR-330 Provided
Assemble by type , Functional ratio @Autowired Less , There is no need to use .
-- Definition Bean Scope and life process
@Scope("prototype")
Value has :singleton,prototype,session,request,session,globalSession
@PostConstruct
amount to init-method, Use it in a way , When Bean Execute on initialization .
@PreDestroy
amount to destory-method, Use it in a way , When Bean When destroyed .
-- Declarative transactions
@Transactional
@Autowired @Resource @Qualifier The difference between
Practical understanding :@Autowired @Resource One of the two , Use whichever you like .
Simple understanding :
@Autowired Inject... According to type ,
@Resource The default is to inject by name , Second, search by type
@Autowired @Qualifie("userService") The combination of the two can be injected according to name and type
Complex understanding :
For example, you have such a Bean
@Service(“UserService”)
public Class UserServiceImpl implements UserService{};
Now you want to be in UserController Use this inside UserServiceImpl
public Class UserController {
@AutoWired // When using this injection, the above UserServiceImpl Just write like this @Service, This will automatically find UserService This type and its subtypes .UserServiceImpl Realized UserService, So I can find it . But this has one drawback , Is that when UserService There are more than two implementation classes , Which one will you look for at this time , This creates conflict , So want to use @AutoWire When injecting, make sure UserService There is only one implementation class .
@Resource By default, match by name , If no one with the same name is found Bean, Will match by type , Someone might think , This is good , Using this is omnipotent , Never mind the name , No matter the type , But there are still shortcomings . First , According to the matching effect of this annotation, we can see , It was matched twice , in other words , If you are in the UserService This class is annotated like this ,@Service, How will it find it , First, find someone with the same name , If not found , Find the same type of , And here it is @Service No name , At this time, I conducted two searches , obviously , The speed drops a lot . Maybe you'll ask , there @Service There was no name , It must be a direct type search . It's not like that ,UserServiceImpl If there is @Service Default name This is it userServiceImpl, Look for the , Is to change the uppercase in front of the class name into lowercase , It's the default Bean The name of . @Resource Search by name is written like this @Resource("userService"), If you write the name userService, that UserServiceImpl It must be the same name , Otherwise, it will be reported wrong .
@Autowired @Qualifie("userService") Search directly by name , in other words , about UserServiceImpl above @Service The annotation must write the name , If you don't write, you'll get a mistake , And the name must be @Autowired @Qualifie("userService") bring into correspondence with . If @Service The name is written on it , and @Autowired @Qualifie() , It will also report mistakes .
private UserService userService;
}
Said so much , Maybe you're a little dizzy , So how to use these three , The actual work should be used according to the actual situation , Usually use AutoWire and @Resource A little more ,bean Don't write your name , and UserServiceImpl It can be written like this @Service("userService"). The actual work here , What is the situation ? To put it bluntly, it is the situation considered in the design of the whole project , If your framework The designer thinks carefully , Strict requirements , It is required that the access speed after the project goes online is better , Speed is usually considered . This is the time @AutoWire No, @Resource To use , because @Resource You can search by name , It's written like this @Resource("userService"). This @Autowired @Qualifie("userService") You can also use a name , Why not , The reason is simple , This is a little long , Don't like , Increase the workload . Because searching by name is the fastest , It's like checking database equally , according to Id Find the fastest . Because the name here is the same as that in the database ID It's the same thing . This is the time , Just ask you to write more names , The workload naturally increases . And if you don't need notes , use xml When you file , For injection Bean When asked to write a Id,xml At the time of the document id It's equivalent to the name here .
It's useless to say so much , What you can do is simple and direct , Use whatever is most convenient ,
You just use @Resource got , If you like it @AutoWired It's OK , Don't write your name .
Usually, there is a Bean The annotation of is wrong , The following errors will be reported , Most commonly ,
No bean named 'user' is defined, This representation is not found and is named user Of Bean, Popular said , The name is user The type of , And its subtypes , The reason for this error is that the type name at the time of injection is user, When searching, I can't find , That is to say, maybe the type of search , There is no order for user, The solution is to find this type , Go to order as user,
The following error is also common ,
No qualifying bean of type [com.service.UserService] found for dependency:
The reason for this error is that the type is not added @Service This injection , not only @Service, This error will also occur in other layers , Here I am with Service Give an example of , If it is DAO Layer is not added @Repository,Controller layer , Is not added @Controller.
also , If you still want to be simpler , Whether it's DAO,Controller,Service Three layers , You can use this annotation ,@Component, This annotation is common to all Bean, At this time, you may say , Why are there usually few people using it , That's because MVC This layered design principle , use @Repository,@Service,@Controller, This can be distinguished MVC In principle DAO,Service,Controller. Easy to identify .
Blog 2:
spring autowired qualifier bytype byname
In the use of Spring In the frame @Autowired Labels are used by default
Java Code
- @Autowired
@AutowiredWhen comments are automatically injected ,Spring Matching candidates in container Bean There must be and only one . When you can't find a match Bean when ,Spring The container will throw BeanCreationException abnormal , And point out that there must be at least one matching Bean.
@Autowired The default is byType For injection , If you find more than one bean, be , According to byName Mode comparison , If there are more , Report an exception .
Example :
@Autowired
private ExamUserMapper examUserMapper; - ExamUserMapper It's an interface
1. spring First find the type ExamUserMapper Of bean
2. If it exists and is unique , be OK;
3. If it's not the only one , In the result set , seek name by examUserMapper Of bean. because bean Of name There is uniqueness , therefore , It should be able to determine whether there is one that meets the requirements bean 了
@Autowired It can also be manually specified according to byName Way into , Use @Qualifier label , for example :
@Autowired () @Qualifier ( "baseDao" )
Spring Allow us to pass
Java Code
- @Qualifier
@Qualifier Note specify injection Bean The name of , In this way, ambiguity is eliminated , Exceptions can be resolved by .
Java Code
- @Qualifier("XXX")
@Qualifier("XXX") Medium XX yes Bean The name of , therefore @Autowired and @Qualifier When used in combination , The strategy of automatic injection starts from byType Into a byName 了 .
@Autowired Member variables can be 、 Method and constructor for comments , and @Qualifier The dimension object of is a member variable 、 Methods into the reference 、 Constructor in parameter .
Spring Not only support your own definition @Autowired annotation , It also supports several JSR-250 A note on the definition of the specification , They are @Resource、@PostConstruct as well as @PreDestroy.
Java Code
- @Resource
@Resource Is equivalent to @Autowired, It's just @Autowired Press byType Automatic injection , and @Resource Press default byName It's just automatic injection [email protected] There are two attributes that are important , Cent is name and type,Spring take @Resource Annotated name Property resolved to bean Name , and type Property resolves to bean The type of . So if you use name attribute , Then use byName Automatic injection strategy of , While using type Property is used byType Automatic injection strategy . If you don't specify name It doesn't specify type attribute , This will be used by the reflection mechanism byName Automatic injection strategy .
@Resource Assembly sequence
1. If you also specify name and type, From Spring Unique match found in context bean Assembly , Throw exception if not found
2. If you specify name, Find name from context (id) Matching bean Assembly , Throw exception if not found
3. If you specify type, Then find the unique type match from the context bean Assembly , Can't find or find more than one , Will throw an exception
4. If neither name, It's not specified type, Then automatically follow the byName Method of assembly ; If there is no match , Back off to match as an original type , Auto assemble if match
边栏推荐
- 简易版 微信小程序开发之for指令、上传图片及展示效果优化
- Application of derivative in daily question
- LVGL使用心得
- VS code配置虚拟环境
- Pytoch lightweight visualization tool wandb (local)
- What happens between entering the URL and displaying the page?
- [MySQL] the difference between left join, right join and join
- MongoDB安装 & 部署
- Agile certification (professional scrum Master) simulation exercises
- 为什么线程崩溃不会导致 JVM 崩溃
猜你喜欢

用Three.js做一個簡單的3D場景
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output](/img/38/9c460fc58b62609dd02e7c61207ae6.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output

Vs Code configure virtual environment

Pytorch multi card distributed training distributeddataparallel usage

User value is the last word in the competition of mobile phone market

Latest version of NPM: the "NPM" item cannot be recognized as the name of a cmdlet, function, script file, or runnable program. Please check

Vs 2019 configuration tensorrt

为什么线程崩溃不会导致 JVM 崩溃

Vs 2019 installation and configuration opencv

Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf
随机推荐
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
Téléchargement et installation du client Filezilla
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
用Three.js做一个简单的3D场景
基于QT的tensorRT加速的yolov5
Limit of one question per day
2020-01-01t00:00:00.000000z date format conversion
Pytorch配置
el-tree搜索方法使用
[mathematical logic] predicate logic (individual word | individual domain | predicate | full name quantifier | existence quantifier | predicate formula | exercise)
MySQL practice 45 lecture [transaction isolation]
Using jasmine to monitor constructors - spying on a constructor using Jasmine
Converts a timestamp to a time in the specified format
labelimg生成的xml文件转换为voc格式
ffmpeg录制屏幕和截屏
监听对象中值变化及访问
@Accessors annotation function specifies that the prefix follows the hump naming
labelme标记的文件转换为yolov5格式
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
[mathematical logic] propositions and connectives (propositions | propositional symbolization | truth connectives | no | conjunction | disjunction | non truth connectives | implication | equivalence)