Java进阶知识18 Spring Bean对象的创建细节和创建方式

本文知识点(目录):

      1、创建细节
         1) 对象创建: 单例/多例
         2) 什么时候创建?
         3)是否延迟创建(懒加载)
         4) 创建对象之后,初始化/销毁
     2、创建方式  
         2.1、默认无参构造器
         2.2、带参构造器(有两种方式,第一种:一个实体类;第二种:两个实体类合为一个[嵌套])
         2.3、工厂类创建对象(两种:一个是工厂实体类,另一个是工厂实体类内部的静态方法)
     3、附录(第二大点“Bean的创建方式”的所有完整代码)



1、创建细节  

  1) 对象创建: 单例/多例
       scope="singleton"   默认值, 即默认是单例 【service/dao/工具类】
       scope="prototype"  多例; 【Action对象】
  2) 什么时候创建?
       scope="singleton"  在启动(容器初始化之前),就已经创建了bean,且整个应用只有一个。
       scope="prototype"  在用到对象的时候,才创建对象。
  3)是否延迟创建(懒加载)
       lazy-init="false"  默认为false,不延迟创建,即在启动(容器初始化之前)时候就创建对象(只对单例有效)
       lazy-init="true"   延迟初始化, 在用到对象的时候才创建对象(只对单例有效)
  4) 创建对象之后,初始化/销毁
       init-method="init_user"   【对应对象的init_user方法,在对象创建之后执行 】
       destroy-method="destroy_user"  【在调用容器对象的destroy方法时候执行,(容器用实现类)】

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:aop="http://www.springframework.org/schema/aop"
 5        xmlns:tx="http://www.springframework.org/schema/tx"
 6        xsi:schemaLocation="
 7        http://www.springframework.org/schema/beans
 8        http://www.springframework.org/schema/beans/spring-beans.xsd
 9        http://www.springframework.org/schema/tx
10        http://www.springframework.org/schema/tx/spring-tx.xsd
11        http://www.springframework.org/schema/aop
12        http://www.springframework.org/schema/aop/spring-aop.xsd">
13   
14   
15       <!-- 
16           id:指定bean对象的id
17           class:指定bean的类,不能用接口
18           scope:单例/多例,默认是“singleton”(此时在初始化容器之前就创建对象),多例:用到的时候才创建
19           lazy-init:懒加载,只针对单例有效,默认是false,如果是true——用到的时候才创建
20           init-method:指定对象的初始化方法,时间由创建对象的时间来决定
21        -->
22        <!-- UserDao userDao = new UserDao() -->
23     <bean id="userDao" class="com.bw.dao.UserDao" scope="singleton" lazy-init="false"
24     init-method="init" destroy-method="destroy"><!-- 默认是单例 -->
25         <property name="name" value="Mr Zhang"></property>
26     </bean>
27     
28     <bean id="userService" class="com.bw.service.UserService" scope="singleton"><!-- 默认是单例 -->
29         <property name="userDao" ref="userDao"></property>
30     </bean>    
31     
32     <bean id="userAction" class="com.bw.action.UserAction" scope="prototype"><!-- 多个 -->
33         <property name="userService" ref="userService"></property>
34     </bean>     
35 </beans>

2、创建方式  

  2.1、默认无参构造器

spring容器

1 <bean id="user1" class="com.shore.entity.User">
2      <property name="id" value="101"></property>
3      <property name="name" value="张三"></property>
4      <property name="sex" value="true"></property>
5 </bean>

User实体类

1 public class User {
2     private Integer id;
3     private String name;
4     private Boolean sex;
5     //set、get和toString方法省略  
6 }

测试类

1 @Test
2  public void test1() { //使用无参构造器创建一个User对象
3       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
4       User user1 = (User) context.getBean("user1");
5       System.out.println(user1.toString()); //返回结果:User [id=101, name=张三, sex=true]
6  }

  2.2、带参构造器

第一种方式:

spring容器

1 <!-- 有参构造器01 -->
2 <bean id="user2" class="com.shore.entity.User">
3     <constructor-arg name="id" value="102" type="java.lang.Integer" /><!-- type可以省略 -->
4     <constructor-arg name="name" value="李四" type="java.lang.String" />
5     <constructor-arg name="sex" value="true" type="java.lang.Boolean" />
6 </bean>

User实体类

 1 public class User {
 2     private Integer id;
 3     private String name;
 4     private Boolean sex;
 5     
 6     public User() {
 7         
 8     }
 9     
10     public User(Integer id, String name, Boolean sex) {
11         super();
12         this.id = id;
13         this.name = name;
14         this.sex = sex;
15     }
16       //set、get和toString方法省略
17 }

测试类

1 @Test
2 public void test2() { //使用无参构造器创建一个User对象
3      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
4      User user2 = (User) context.getBean("user2");
5      System.out.println(user2.toString()); //返回结果:User [id=102, name=李四, sex=true]
6 }

第二种方式:

spring容器

 1 <!-- 有参构造器02 -->
 2 <bean id="str" class="com.shore.entity.Company">
 3       <constructor-arg index="0" value="华为技术有限公司"></constructor-arg>
 4       <constructor-arg index="1" value="广东省深圳市xxxxx"></constructor-arg>
 5 </bean> <!-- index的值从0开始,value的值要与构造器的字段的顺序对应 -->
 6 <bean id="user3" class="com.shore.entity.User">
 7      <constructor-arg index="0" value="103" type="java.lang.Integer" />
 8      <constructor-arg index="1" value="王五" type="java.lang.String" />
 9      <constructor-arg index="2" value="true" type="java.lang.Boolean" />
10      <constructor-arg index="3" type="java.util.Set" ref="str" /> <!-- ref:参照-->
11 </bean>

User实体类

 1 public class User {
 2     private Integer id;
 3     private String name;
 4     private Boolean sex;
 5     private Set<Company> company = new HashSet<Company>();
 6     
 7     public User() {
 8         
 9     }
10     
11     public User(Integer id, String name, Boolean sex, Set<Company> company) {
12         super();
13         this.id = id;
14         this.name = name;
15         this.sex = sex;
16         this.company = company;
17     }
18       //下面省略了set、get和toString方法
19 }

Company实体类

 1 public class Company {
 2     private String name; //公司名称
 3     private String address; //地址
 4     
 5     public Company() {
 6     }
 7     
 8     public Company(String name, String address) {
 9         super();
10         this.name = name;
11         this.address = address;
12     }
13    //下面省略了 set、get和toString方法   
14 }

测试类

1 @Test
2     public void test3() { //使用有参构造器创建一个User对象02
3         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
4         User user3 = (User) context.getBean("user3");
5         System.out.println(user3.toString()); //返回结果:User [id=103, name=王五, sex=true, company=[Company [name=华为技术有限公司, address=广东省深圳市xxxxx]]]
6     }

  2.3、工厂类创建对象

spring容器

1 <!-- 工厂模式创建实例对象 --> 
2 <bean id="factory" class="com.shore.factory.StudentFactory"></bean>
3 <bean id="student1" factory-bean="factory" factory-method="getInstance"></bean>

Student实体类

 1 public class Student {
 2     private Integer id;
 3     private String name;
 4     private Boolean sex;
 5     
 6     public Student() {
 7         
 8     }
 9     
10     public Student(Integer id, String name, Boolean sex) {
11         super();
12         this.id = id;
13         this.name = name;
14         this.sex = sex;
15     }
16       //下面省略了set、get和toString方法
17 }

StudentFactory实体类

1 public class StudentFactory {
2     // 实例方法创建对象
3     public Student getInstance() {
4         return new Student(104,"实例方法创建对象",true);
5     }
6 }

测试类

1 @Test
2     public void test4() { //使用工厂创建一个Student对象
3         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
4         Student student1 = (Student) context.getBean("student1");
5         System.out.println(student1.toString()); //返回结果:Student [id=104, name=实例方法创建对象, sex=true]
6     }

  2.4、使用工厂类的静态方法创建对象

spring容器

1 <!-- 工厂模式静态方法创建实例对象 -->
2 <bean id="student2" class="com.shore.factory.StudentFactory" factory-method="getStaticInstance"></bean>

StudentFactory实体类

1 public class StudentFactory {
2     //静态方法创建一个实例对象
3     public static Student getStaticInstance() {
4         return new Student(105,"静态方法创建对象",false);
5     }
6 }

测试类

1 @Test
2     public void test5() { //使用工厂静态方法创建一个Student对象象
3         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
4         Student student2 = (Student) context.getBean("student2");
5         System.out.println(student2.toString()); //返回结果:Student [id=105, name=静态方法创建对象, sex=false]
6     }

 

 

  附录  

上面第二大点“创建方式”的所有完整代码

User实体类

 1 package com.shore.entity;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 /**
 7  * @author DSHORE/2019-10-16
 8  *
 9  */
10 public class User {
11     private Integer id;
12     private String name;
13     private Boolean sex;
14     private Set<Company> company = new HashSet<Company>();
15     
16     public User() {
17         
18     }
19     
20     public User(Integer id, String name, Boolean sex, Set<Company> company) {
21         super();
22         this.id = id;
23         this.name = name;
24         this.sex = sex;
25         this.company = company;
26     }
27 
28     public Integer getId() {
29         return id;
30     }
31     public void setId(Integer id) {
32         this.id = id;
33     }
34     
35     public String getName() {
36         return name;
37     }
38     public void setName(String name) {
39         this.name = name;
40     }
41     
42     public Boolean getSex() {
43         return sex;
44     }
45     public void setSex(Boolean sex) {
46         this.sex = sex;
47     }
48 
49     public Set<Company> getCompany() {
50         return company;
51     }
52 
53     public void setCompany(Set<Company> company) {
54         this.company = company;
55     }
56 
57     @Override
58     public String toString() {
59         return "User [id=" + id + ", name=" + name + ", sex=" + sex
60                 + ", company=" + company + "]";
61     }
62 }

Company实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2019-10-16
 5  *
 6  */
 7 public class Company {
 8     private String name; //公司名称
 9     private String address; //地址
10     
11     public Company() {
12     }
13     
14     public Company(String name, String address) {
15         super();
16         this.name = name;
17         this.address = address;
18     }
19 
20     public String getName() {
21         return name;
22     }
23     public void setName(String name) {
24         this.name = name;
25     }
26     public String getAddress() {
27         return address;
28     }
29     public void setAddress(String address) {
30         this.address = address;
31     }
32 
33     @Override
34     public String toString() {
35         return "Company [name=" + name + ", address=" + address + "]";
36     }
37 }

Student实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2019-10-16
 5  *
 6  */
 7 public class Student {
 8     private Integer id;
 9     private String name;
10     private Boolean sex;
11     
12     public Student() {
13         
14     }
15     
16     public Student(Integer id, String name, Boolean sex) {
17         super();
18         this.id = id;
19         this.name = name;
20         this.sex = sex;
21     }
22     
23     public Integer getId() {
24         return id;
25     }
26     public void setId(Integer id) {
27         this.id = id;
28     }
29     
30     public String getName() {
31         return name;
32     }
33     public void setName(String name) {
34         this.name = name;
35     }
36     
37     public Boolean getSex() {
38         return sex;
39     }
40     public void setSex(Boolean sex) {
41         this.sex = sex;
42     }
43     
44     @Override
45     public String toString() {
46         return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
47     }
48 }

StudentFactory实体类

 1 package com.shore.factory;
 2 
 3 import com.shore.entity.Student;
 4 
 5 /**
 6  * @author DSHORE/2019-10-16
 7  *
 8  */
 9 public class StudentFactory {
10     // 实例方法创建对象
11     public Student getInstance() {
12         return new Student(104,"实例方法创建对象",true);
13     }
14     
15     //静态方法创建一个实例对象
16     public static Student getStaticInstance() {
17         return new Student(105,"静态方法创建对象",false);
18     }
19 }

Spring容器(applicationContext.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:tx="http://www.springframework.org/schema/tx"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xmlns:context="http://www.springframework.org/schema/context"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans
 8             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
 9             http://www.springframework.org/schema/tx
10             http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
11             http://www.springframework.org/schema/aop
12             http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
13             http://www.springframework.org/schema/context
14             http://www.springframework.org/schema/context/spring-context-3.2.xsd">
15                                                <!-- 后面的3.2:这些版本号,要与你引入的包的版本号一致  -->
16            <!-- 默认无参构造器 -->
17         <!-- 当spring框架加载时,spring会自动创建一个bean对象,相当于User user1 = new User(); 调用了set方法给每个属性注入值 -->    
18            <bean id="user1" class="com.shore.entity.User">
19                <property name="id" value="101"></property>
20             <property name="name" value="张三"></property>
21             <property name="sex" value="true"></property>
22            </bean>
23            
24         <!-- 有参构造器01 -->
25         <!-- User user2 = new User(249,"李四",true) -->
26         <!-- <bean id="user2" class="com.shore.entity.User">
27             <constructor-arg name="id" value="102" type="java.lang.Integer" />type可以省略
28             <constructor-arg name="name" value="李四" type="java.lang.String" />
29             <constructor-arg name="sex" value="true" type="java.lang.Boolean" />
30         </bean> -->
31        
32         <!-- 有参构造器02 -->
33         <!-- User user3 = new User(103,"王五",true,company) -->
34         <bean id="str" class="com.shore.entity.Company">
35             <constructor-arg index="0" value="华为技术有限公司"></constructor-arg>
36             <constructor-arg index="1" value="广东省深圳市xxxxx"></constructor-arg>
37         </bean> <!-- index的值从0开始,value的值要与构造器的字段的顺序对应 -->
38         <bean id="user3" class="com.shore.entity.User">
39             <constructor-arg index="0" value="103" type="java.lang.Integer" />
40             <constructor-arg index="1" value="王五" type="java.lang.String" />
41             <constructor-arg index="2" value="true" type="java.lang.Boolean" />
42             <constructor-arg index="3" type="java.util.Set" ref="str" />
43         </bean>
44        
45         <!-- 工厂模式创建实例对象 --> 
46         <bean id="factory" class="com.shore.factory.StudentFactory"></bean>
47         <bean id="student1" factory-bean="factory" factory-method="getInstance"></bean>
48         
49         <!-- 工厂模式静态方法创建实例对象 -->
50         <bean id="student2" class="com.shore.factory.StudentFactory" factory-method="getStaticInstance"></bean>
51            
52 </beans>

测试类

 1 package com.shore.test;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 import com.shore.entity.Student;
 8 import com.shore.entity.User;
 9 
10 /**
11  * @author DSHORE/2019-10-16
12  *
13  */
14 public class MyTest {
15     @Test
16     public void test1() { //使用无参构造器创建一个User对象
17         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
18         User user1 = (User) context.getBean("user1");
19         System.out.println(user1.toString());//返回结果:User [id=101, name=张三, sex=true]
20     }
21 
22     @Test
23     public void test2() { //使用有参构造器创建一个User对象01
24         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
25         User user2 = (User) context.getBean("user2");
26         System.out.println(user2.toString());//返回结果:User [id=102, name=李四, sex=true]
27     }
28     
29     @Test
30     public void test3() { //使用有参构造器创建一个User对象02
31         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
32         User user3 = (User) context.getBean("user3");
33         System.out.println(user3.toString()); //返回结果:User [id=103, name=王五, sex=true, company=[Company [name=华为技术有限公司, address=广东省深圳市xxxxx]]]
34     }
35     
36     @Test
37     public void test4() { //使用工厂创建一个Student对象
38         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
39         Student student1 = (Student) context.getBean("student1");
40         System.out.println(student1.toString()); //返回结果:Student [id=104, name=实例方法创建对象, sex=true]
41     }
42     
43     @Test
44     public void test5() { //使用工厂静态方法创建一个Student对象象
45         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
46         Student student2 = (Student) context.getBean("student2");
47         System.out.println(student2.toString()); //返回结果:Student [id=105, name=静态方法创建对象, sex=false]
48     }
49 }

 

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/11686438.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

 

2)带参构造器

posted @ 2019-10-16 16:41  DSHORE  阅读(912)  评论(0编辑  收藏  举报