Spring learning 03

spring learning


6、Bean Automatic assembly of

6.1 Automatic assembly instructions

  • Automatic assembly is the use of spring Satisfy bean A method of dependency

  • spring In the context of an application bean Look for what it depends on bean.

Spring in bean Three kinds of assembly mechanism based on virtual reality :

  1. stay xml Explicitly configure ;

  2. stay java Explicitly configure ;

  3. implicit bean Discovery mechanism and automatic assembly .

Here's the main thing : Automated assembly bean.

Spring The automatic assembly needs to be realized from two aspects , Or two operations :

  1. Component scan (component scanning):spring It will automatically discover the bean;

  2. Automatic assembly (autowiring):spring Automatically meet bean Dependence between , That's what we're talking about IoC/DI;

The combination of component scanning and automatic assembly is powerful , The display configuration is minimized .

 

6.2 Test environment construction

1、 Create a new project

2、 Create two new entity classes ,Cat Dog There's a way to call it

public class Cat {
public void shout() {
System.out.println("miao~");
}
}
public class Dog {
public void shout() {
System.out.println("wang~");
}
}

3、 Create a new user class User

public class User {
private Cat cat;
private Dog dog;
private String str;
}

4、 To write Spring The configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat" class="com.chen.pojo.Cat"/><bean id="user" class="com.chen.pojo.User">
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
<property name="str" value="chen"/>
</bean>
</beans>

5、 test

public class MyTest {
@Test
public void testMethodAutowire() {
ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.getCat().shout();
user.getDog().shout();
}
}

 

6.3 byName Automatic assembly

autowire byName ( Automatic assembly by name )

Due to manual configuration xml In the process , Errors such as missing letters and case letters often occur , And you can't check it , Reduce the efficiency of development .

Using automatic assembly will avoid these mistakes , And make the configuration simple .

test :

1、 modify bean To configure , Add a property autowire="byName"

<bean id="user" class="com.chen.pojo.User" autowire="byName">
<property name="str" value="chen"/>
</bean>

2、 The test again , The result is still output successfully !

3、 We will cat Of bean id It is amended as follows cat11

4、 The test again , Execution time null pointer  java.lang.NullPointerException . Because press byName Rules don't match set Method , real setCat It's not implemented , The object is not initialized , Therefore, a null pointer error will be reported when calling .

Summary :

When one bean Node with autowire byName When the properties of the .

  1. Will find all of the set Method name , for example setCat, Gain will set Remove and lower case initial strings , namely cat.

  2. Go to spring Container to find if there is this string name id The object of .

  3. If there is , Take it out and inject it ; without , The null pointer exception is reported .

     

6.4 byType Automatic assembly

autowire byType ( Automatic assembly by type )

Use autowire byType First of all, we need to make sure that : Objects of the same type , stay spring The only one in the container . If it's not the only one , It will report more than one exception  NoUniqueBeanDefinitionException .

test :

1、 take user Of bean Change the configuration : autowire="byType"

2、 test , Normal output

3、 Sign up for a cat Of bean object !

<bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat" class="com.chen.pojo.Cat"/>
<bean id="cat2" class="com.chen.pojo.Cat"/><bean id="user" class="com.chen.pojo.User" autowire="byType">
<property name="str" value="chen"/>
</bean>

4、 test , Report errors :NoUniqueBeanDefinitionException

5、 Delete cat2, take cat Of bean Change the name ! test ! Because it's assembled by type , So no exception will be reported , It doesn't affect the final result . Even the id Attributes to remove , It doesn't affect the results .

This is automatic assembly by type .

 

6.5 Automatic assembly using annotations

Using annotations

jdk1.5 Start supporting annotations ,spring2.5 Start to fully support annotations .

preparation : Use annotation to inject attributes .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"><!-- Turn on annotation support -->
<context:annotation-config/></beans>

 

@Autowired

  • @Autowired It's automatically assembled by type , I won't support it id matching .

  • Import required spring-aop My bag !

test :

1、 take User Class set Methods to remove , Use @Autowired annotation

public class User {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String str;
​
public Cat getCat() {
return cat;
}
public Dog getDog() { return dog; } public String getStr() { return str; } }

2、 At this point, the configuration file content

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config/><bean id="dog" class="com.chen.pojo.Dog"/> <bean id="cat" class="com.chen.pojo.Cat"/> <bean id="user" class="com.chen.pojo.User"/>

</beans>

3、 test , Successful output results .

 

@Autowired(required=false)

explain :false, The object can be null;true, Objects must hold objects , Not for null.

// If the object is allowed to be null, Set up required = false, The default is true
@Autowired(required = false)
private Cat cat;

 

@Qualifier

  • @Autowired It's automatically assembled according to the type , add @Qualifier According to byName The way of automatic assembly

  • @Qualifier Not to be used alone .

test

1、 Configuration file changes , Ensure that the type exists the object . And the name is not the default name of the class !

<bean id="dog1" class="com.chen.pojo.Dog"/>
<bean id="dog2" class="com.chen.pojo.Dog"/>
<bean id="cat1" class="com.chen.pojo.Cat"/>
<bean id="cat2" class="com.chen.pojo.Cat"/>

2、 No addition Qualifier test , Direct error

3、 Add... To the attribute Qualifier annotation

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

test , Output successful .

 

@Resource

  • @Resource If specified name attribute , Press the attribute first byName How to find the assembly ;

  • Secondly, the default byName Method of assembly ;

  • If none of the above is successful , Then press byType The way of automatic assembly .

  • Don't successful , Abnormal Report .

Entity class :

public class User {
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}

xml:

<bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat1" class="com.chen.pojo.Cat"/>
<bean id="cat2" class="com.chen.pojo.Cat"/>
<bean id="user" class="com.chen.pojo.User"/>

Test success .

Delete cat2

<bean id="dog" class="com.chen.pojo.Dog"/>
<bean id="cat1" class="com.chen.pojo.Cat"/><bean id="user" class="com.chen.pojo.User"/>

Only annotations are kept on entity classes

@Resource
private Cat cat;
@Resource
private Dog dog;

Test success .

 

Summary

@Autowired And @Resource similarities and differences :

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 ( Belong to spring standard ), 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 you want to use the name assembly, you can combine @Qualifier Use annotations

3、@Resource( Belong to J2EE return ), 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 by 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 .

They do the same thing by injecting objects with annotations , But the execution order is different .@Autowired First byType,@Resource First byName.




版权声明
本文为[There are no bugs in this line of code]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210123155243112c.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云