Spring annotation of @ Autowired, @ Qualifier, @ Resource, @ Value Spring annotation of @ Autowired, @ Qualifier, @ Resource, @ Value

Excerpt: https://www.cnblogs.com/yichunguo/p/12110755.html

Spring annotation of @ Autowired, @ Qualifier, @ Resource, @ Value

 

Introduction
@ Autowired, @ Qualifier, @ Resource , @ Value four notes are used to inject data, their role is and bean tag in the xml configuration file written in a label that is the same! This blog entry to explain the special focus is @Autowired comment

1, a first scenario is given

@Autowired comment before speaking to a given scenario:

dao level code

@Repository
public class AccountDao {
    public void save() {
        System.out.println("dao数据save成功了...."); } }

service level code

@Service
public class AccountImpl implements AccountService { private AccountDao accountDao; @Override public void save() { accountDao.save(); } }

Presentation layer controller Code:

//模拟一个表现层功能
public class AccountController {
    public static void main(String[] args) { //1.获取核心容器对象 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("Applicationcontext.xml"); //2.根据id获取Bean对象 AccountService as = (AccountService)ac.getBean("accountImpl"); as.save(); System.out.println(as); } }

Operating results
Here Insert Picture Description
I believe we java.lang.NullPointerExceptionnull-pointer exceptions have become accustomed to, especially cordial .....

So why is there this anomaly it? Obviously you can see from the code out of the service with  AccountDao the type of property is not injected into the anomaly caused by a null pointer, then the rest is to @Autowired comment debut ....

2、@Autowired

Spring 2.5 introduces @Autowired annotations, it can be labeled class fields, methods and constructors, parameters and the like used mainly in [ variables and methods on], to complete the automatic assembly work. By using @Autowired to eliminate set, get method, that is, the use of injection @Autowired annotation attribute data set does not need this class provides methods, convenient and quick . @AutowiredAnd on the role of bean tag in the xml configuration file written in a < property >label of the role is the same.

In the previous article on how to use the factory pattern implementation program decoupling in Spring? We more or less know the underlying spring IOC is actually a Map structure of the container, the so-called key is the bean tag id, value is the label of the corresponding bean class .

@Autowired automatic assembling will be skipped IOC first attribute corresponding to a container vessel directly to the key found! That has nothing to do with the key.

Automatic assembly @Autowired three cases:

1, the vessel has only one bean object types and are @Autowired modified variable type matching, you can inject success!
2, the container is not a bean @Autowired modified object type and a variable type matching, the operation fails injection being given.
3, there are multiple bean container object types and are @Autowired modified variable types match, then find @Autowired be modified according to the variable name, find the successful injection [ focus ]

Many people will ignore or do not know the third point! ! !

3、@Qualifier

According to the third case @Autowired above, we need to change the variable name to the corresponding injection, so the program is not very flexible, so with @Qualifier this comment. @Qualifier effect of implantation by name, then the base class in accordance with the above implantation. It can not be used when a single injection to the class members (alone may be used when a parameter injection method), so @Qualifier annotation very limited, and therefore not much used. @Qualifier often used in combination with @Autowired, it is used to indicate the specific name of automatic assembly


    @Autowired //如果单纯一个@Autowired 注解则表示找类型为IAccuntDao的,如果有两个类型为IAccuntDao的,则接着匹配类型为IAccuntDao而且名字为accountDao的【缺点:要改变量名指定】
    @Qualifier("accountDao2") //加上这个注解直接找类型为IAccuntDao而且名字为accountDao的
    private IAccuntDao accountDao;
    
    所以这段代码注解的意思就是直接找类型为IAccuntDao而且名字为accountDao的组件

In fact, the above comments equivalent to the following notes, we'll come back:

 @Resource("accountDao2")
 private IAccuntDao accountDao;

4、@Resource

@Resource provided by J2EE, according to byName default is automatically injected (by name automatically injected), @ Resource There are two important properties, name, and type, of course, default by name, there is no need to talk about the type attribute, use the type attribute superfluous, might as well use @Autowired, so for @Resource Remember automatically injected by name!

5, the difference between @ Autowired, @ Resource of

I had said that the two notes are very similar and are easily confused.

@ Autowired, the main difference @ Resource mainly the following points:

  @Autowired @Resource
Notes provider Spring J2EE
Mode automatic assembly Attributes first name

In fact, the main difference is the two points, of course, are bound to have the details, here temporarily outlines.

Of course, the more important point is: @Resource equivalent @Autowired + @Qualifier

6、@Value

Because @ Autowired, @ Qualifier, @ Resource for only three automatic assembly to inject other bean types of data, and the basic types and String types can not be used to achieve the above comment. So there is @Value this annotation, @ Value devoted to the basic service types and String.

Further @Value annotation has a property value: a value for the specified data. It can be used in spring SpEL (ie spring EL expression). SpEL wording: $ {} expression, of course, also be similarly mybatis the expression {#} wording

@Value("#{2*3}")  //#写法 表示6
private int age;

@Value("178")    //普遍写法 178
private int height;

@Value("${man.weight}") //SpEL的写法一般操作配置文件中数据 private int weight;

Note: The type of collection can only be achieved by injecting XML

7 Summary

More @ Autowired, @ Qualifier, @ Resource, @ Value four notes are used to inject data, their role is and bean tag in the xml configuration file written in a label that is the same!

If this article there is a little bit of help to you, then please point a praise chant, you agree is my greatest motivation, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, there are some java learning materials and a large wave of java e-books, such as Zhou Zhiming teacher depth java virtual machine, java programming ideas, the core technology volume, Westward design patterns, java concurrent programming combat ... .. is a java Bible, do not say fast car on Tomcat, ye who go! The main thing is to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Did not fly every day to live up to is a kind of life ....
 

Introduction
@ Autowired, @ Qualifier, @ Resource , @ Value four notes are used to inject data, their role is and bean tag in the xml configuration file written in a label that is the same! This blog entry to explain the special focus is @Autowired comment

1, a first scenario is given

@Autowired comment before speaking to a given scenario:

dao level code

@Repository
public class AccountDao {
    public void save() {
        System.out.println("dao数据save成功了...."); } }

service level code

@Service
public class AccountImpl implements AccountService { private AccountDao accountDao; @Override public void save() { accountDao.save(); } }

Presentation layer controller Code:

//模拟一个表现层功能
public class AccountController {
    public static void main(String[] args) { //1.获取核心容器对象 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("Applicationcontext.xml"); //2.根据id获取Bean对象 AccountService as = (AccountService)ac.getBean("accountImpl"); as.save(); System.out.println(as); } }

Operating results
Here Insert Picture Description
I believe we java.lang.NullPointerExceptionnull-pointer exceptions have become accustomed to, especially cordial .....

那么为啥会出现这个异常呢?很显然从代码中可以看出来service中有着 AccountDao 类型的属性没有注入而引发的空指针异常,那么接下来就到@Autowired注解登场了....

2、@Autowired

Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数、参数等进行标注【主要还是用在变量方法上】,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法,也就是说,使用@Autowired注解注入属性数据不需要这个类提供set方法,方便快捷@Autowired作用就和在xml配置文件中的bean标签中写一个< property >标签的作用是一样的。

在之前的文章Spring中如何使用工厂模式实现程序解耦?中,我们多多少少知道spring的IOC底层实际上就是一个Map结构容器,所谓key 就是 bean标签 中的 id,value 则是对应 bean标签 中的 class

@Autowired自动装配首先会在IOC容器中跳过key直接去容器中找到对应的属性!也就是说与key无关。

@Autowired自动装配的三种情况:

1、容器中有唯一的一个bean对象类型和被@Autowired修饰的变量类型匹配,就可以注入成功!
2、容器中没有一个bean对象类型和被@Autowired修饰的变量类型匹配,则注入失败运行报错。
3、容器中有多个bean对象类型和被@Autowired修饰的变量类型匹配,则根据被@Autowired修饰的变量名寻找,找到则注入成功【重点

很多人会忽略或者不清楚第三点!!!

3、@Qualifier

根据上面@Autowired的第三种情况,需要更改变量名来对应注入,这样就对程序不是很灵活,于是有了@Qualifier这个注解。@Qualifier的作用是在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用(但是在给方法参数注入时可以单独使用),因此@Qualifier注解很受限制,因此用的不是很多。@Qualifier常常组合@Autowired一起使用,用来指明具体名字的自动装配


    @Autowired //如果单纯一个@Autowired 注解则表示找类型为IAccuntDao的,如果有两个类型为IAccuntDao的,则接着匹配类型为IAccuntDao而且名字为accountDao的【缺点:要改变量名指定】
    @Qualifier("accountDao2") //加上这个注解直接找类型为IAccuntDao而且名字为accountDao的
    private IAccuntDao accountDao;
    
    所以这段代码注解的意思就是直接找类型为IAccuntDao而且名字为accountDao的组件

其实上面的注解等价于下面的注解,我们后面会讲到:

 @Resource("accountDao2")
 private IAccuntDao accountDao;

4、@Resource

@Resource由J2EE提供,默认是按照byName自动注入(通过名字自动注入),@Resource有两个重要的属性,name和type,当然默认是通过name,这里type属性就没必要讲了,用type属性多此一举,还不如用@Autowired,因此对于@Resource记住通过名字自动注入就好了

5、@Autowired、@Resource的区别

不得不说这两个注解非常相似,而且很容易混淆。

@Autowired、@Resource的主要区别主要有下面几点:

  @Autowired @Resource
注解提供者 Spring J2EE
自动装配方式 属性 名字

其实主要的区别就这一两点,当然也肯定有着细节,这里就暂时不概述了。

Of course, the more important point is: @Resource equivalent @Autowired + @Qualifier

6、@Value

Because @ Autowired, @ Qualifier, @ Resource for only three automatic assembly to inject other bean types of data, and the basic types and String types can not be used to achieve the above comment. So there is @Value this annotation, @ Value devoted to the basic service types and String.

Further @Value annotation has a property value: a value for the specified data. It can be used in spring SpEL (ie spring EL expression). SpEL wording: $ {} expression, of course, also be similarly mybatis the expression {#} wording

@Value("#{2*3}")  //#写法 表示6
private int age;

@Value("178")    //普遍写法 178
private int height;

@Value("${man.weight}") //SpEL的写法一般操作配置文件中数据 private int weight;

Note: The type of collection can only be achieved by injecting XML

7 Summary

More @ Autowired, @ Qualifier, @ Resource, @ Value four notes are used to inject data, their role is and bean tag in the xml configuration file written in a label that is the same!

If this article there is a little bit of help to you, then please point a praise chant, you agree is my greatest motivation, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, there are some java learning materials and a large wave of java e-books, such as Zhou Zhiming teacher depth java virtual machine, java programming ideas, the core technology volume, Westward design patterns, java concurrent programming combat ... .. is a java Bible, do not say fast car on Tomcat, ye who go! The main thing is to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/xichji/p/12122618.html