本文知识点(目录):

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方法时候执行,(容器用实现类)】

 <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--
id:指定bean对象的id
class:指定bean的类,不能用接口
scope:单例/多例,默认是“singleton”(此时在初始化容器之前就创建对象),多例:用到的时候才创建
lazy-init:懒加载,只针对单例有效,默认是false,如果是true——用到的时候才创建
init-method:指定对象的初始化方法,时间由创建对象的时间来决定
-->
<!-- UserDao userDao = new UserDao() -->
<bean id="userDao" class="com.bw.dao.UserDao" scope="singleton" lazy-init="false"
init-method="init" destroy-method="destroy"><!-- 默认是单例 -->
<property name="name" value="Mr Zhang"></property>
</bean> <bean id="userService" class="com.bw.service.UserService" scope="singleton"><!-- 默认是单例 -->
<property name="userDao" ref="userDao"></property>
</bean> <bean id="userAction" class="com.bw.action.UserAction" scope="prototype"><!-- 多个 -->
<property name="userService" ref="userService"></property>
</bean>
</beans>

2、创建方式

  2.1、默认无参构造器

spring容器

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

User实体类

 public class User {
private Integer id;
private String name;
private Boolean sex;
//set、get和toString方法省略
}

测试类

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

  2.2、带参构造器

第一种方式:

spring容器

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

User实体类

 public class User {
private Integer id;
private String name;
private Boolean sex; public User() { } public User(Integer id, String name, Boolean sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
//set、get和toString方法省略
}

测试类

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

第二种方式:

spring容器

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

User实体类

 public class User {
private Integer id;
private String name;
private Boolean sex;
private Set<Company> company = new HashSet<Company>(); public User() { } public User(Integer id, String name, Boolean sex, Set<Company> company) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.company = company;
}
//下面省略了set、get和toString方法
}

Company实体类

 public class Company {
private String name; //公司名称
private String address; //地址 public Company() {
} public Company(String name, String address) {
super();
this.name = name;
this.address = address;
}
//下面省略了 set、get和toString方法
}

测试类

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

  2.3、工厂类创建对象

spring容器

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

Student实体类

 public class Student {
private Integer id;
private String name;
private Boolean sex; public Student() { } public Student(Integer id, String name, Boolean sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
//下面省略了set、get和toString方法
}

StudentFactory实体类

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

测试类

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

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

spring容器

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

StudentFactory实体类

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

测试类

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

附录

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

User实体类

 package com.shore.entity;

 import java.util.HashSet;
import java.util.Set; /**
* @author DSHORE/2019-10-16
*
*/
public class User {
private Integer id;
private String name;
private Boolean sex;
private Set<Company> company = new HashSet<Company>(); public User() { } public User(Integer id, String name, Boolean sex, Set<Company> company) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.company = company;
} public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
} public Set<Company> getCompany() {
return company;
} public void setCompany(Set<Company> company) {
this.company = company;
} @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex
+ ", company=" + company + "]";
}
}

Company实体类

 package com.shore.entity;

 /**
* @author DSHORE/2019-10-16
*
*/
public class Company {
private String name; //公司名称
private String address; //地址 public Company() {
} public Company(String name, String address) {
super();
this.name = name;
this.address = address;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} @Override
public String toString() {
return "Company [name=" + name + ", address=" + address + "]";
}
}

Student实体类

 package com.shore.entity;

 /**
* @author DSHORE/2019-10-16
*
*/
public class Student {
private Integer id;
private String name;
private Boolean sex; public Student() { } public Student(Integer id, String name, Boolean sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
} public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
} @Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}

StudentFactory实体类

 package com.shore.factory;

 import com.shore.entity.Student;

 /**
* @author DSHORE/2019-10-16
*
*/
public class StudentFactory {
// 实例方法创建对象
public Student getInstance() {
return new Student(104,"实例方法创建对象",true);
} //静态方法创建一个实例对象
public static Student getStaticInstance() {
return new Student(105,"静态方法创建对象",false);
}
}

Spring容器(applicationContext.xml)

 <?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 后面的3.2:这些版本号,要与你引入的包的版本号一致 -->
<!-- 默认无参构造器 -->
<!-- 当spring框架加载时,spring会自动创建一个bean对象,相当于User user1 = new User(); 调用了set方法给每个属性注入值 -->
<bean id="user1" class="com.shore.entity.User">
<property name="id" value="101"></property>
<property name="name" value="张三"></property>
<property name="sex" value="true"></property>
</bean> <!-- 有参构造器01 -->
<!-- User user2 = new User(249,"李四",true) -->
<!-- <bean id="user2" class="com.shore.entity.User">
<constructor-arg name="id" value="102" type="java.lang.Integer" />type可以省略
<constructor-arg name="name" value="李四" type="java.lang.String" />
<constructor-arg name="sex" value="true" type="java.lang.Boolean" />
</bean> --> <!-- 有参构造器02 -->
<!-- User user3 = new User(103,"王五",true,company) -->
<bean id="str" class="com.shore.entity.Company">
<constructor-arg index="0" value="华为技术有限公司"></constructor-arg>
<constructor-arg index="1" value="广东省深圳市xxxxx"></constructor-arg>
</bean> <!-- index的值从0开始,value的值要与构造器的字段的顺序对应 -->
<bean id="user3" class="com.shore.entity.User">
<constructor-arg index="0" value="103" type="java.lang.Integer" />
<constructor-arg index="1" value="王五" type="java.lang.String" />
<constructor-arg index="2" value="true" type="java.lang.Boolean" />
<constructor-arg index="3" type="java.util.Set" ref="str" />
</bean> <!-- 工厂模式创建实例对象 -->
<bean id="factory" class="com.shore.factory.StudentFactory"></bean>
<bean id="student1" factory-bean="factory" factory-method="getInstance"></bean> <!-- 工厂模式静态方法创建实例对象 -->
<bean id="student2" class="com.shore.factory.StudentFactory" factory-method="getStaticInstance"></bean> </beans>

测试类

 package com.shore.test;

 import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.shore.entity.Student;
import com.shore.entity.User; /**
* @author DSHORE/2019-10-16
*
*/
public class MyTest {
@Test
public void test1() { //使用无参构造器创建一个User对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user1 = (User) context.getBean("user1");
System.out.println(user1.toString());//返回结果:User [id=101, name=张三, sex=true]
} @Test
public void test2() { //使用有参构造器创建一个User对象01
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user2 = (User) context.getBean("user2");
System.out.println(user2.toString());//返回结果:User [id=102, name=李四, sex=true]
} @Test
public void test3() { //使用有参构造器创建一个User对象02
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user3 = (User) context.getBean("user3");
System.out.println(user3.toString()); //返回结果:User [id=103, name=王五, sex=true, company=[Company [name=华为技术有限公司, address=广东省深圳市xxxxx]]]
} @Test
public void test4() { //使用工厂创建一个Student对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student1 = (Student) context.getBean("student1");
System.out.println(student1.toString()); //返回结果:Student [id=104, name=实例方法创建对象, sex=true]
} @Test
public void test5() { //使用工厂静态方法创建一个Student对象象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student2 = (Student) context.getBean("student2");
System.out.println(student2.toString()); //返回结果:Student [id=105, name=静态方法创建对象, sex=false]
}
}

原创作者:DSHORE

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

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

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

2)带参构造器

Java进阶知识17 Spring Bean对象的创建细节和创建方式的更多相关文章

  1. Java进阶知识15 Spring的基础配置详解

    1.SSH各个的职责 Struts2:是web框架(管理jsp.action.actionform等).Hibernate:是ORM框架,处于持久层.Spring:是一个容器框架,用于配置bean,并 ...

  2. Java进阶知识20 Spring的代理模式

    本文知识点(目录): 1.概念  2.代理模式      2.1.静态代理      2.2.动态代理      2.3.Cglib子类代理 1.概念 1.工厂模式  2. 单例模式 代理(Proxy ...

  3. Java进阶知识18 Spring对象依赖关系的几种写法

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  4. Java进阶知识25 Spring与Hibernate整合到一起

    1.概述 1.1.Spring与Hibernate整合关键点 1) Hibernate的SessionFactory对象交给Spring创建.    2) hibernate事务交给spring的声明 ...

  5. Java进阶知识23 Spring对JDBC的支持

    1.最主要的代码 Spring 配置文件(beans.xml) <!-- 连接池 --> <bean id="dataSource" class="co ...

  6. Java进阶知识24 Spring的事务管理(事务回滚)

    1.事务控制概述   1.1.编程式事务控制         自己手动控制事务,就叫做编程式事务控制.         Jdbc代码: connection.setAutoCommit(false); ...

  7. Java进阶知识22 Spring execution 切入点表达式

    1.概述   切入点(execution ):可以对指定的方法进行拦截,从而给指定的类生成代理对象.(拦截谁,就是在谁那里切入指定的程序/方法) 格式: execution(modifiers-pat ...

  8. Java进阶知识21 Spring的AOP编程

    1.概述 Aop:(Aspect Oriented Programming)面向切面编程          功能: 让关注点代码与业务代码分离! 关注点:重复代码就叫做关注点:切面: 关注点形成的类, ...

  9. Java进阶知识16 Spring创建IOC容器的两种方式

    1.直接得到 IOC 容器对象 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app ...

随机推荐

  1. 适合新手的160个creakme(二)

    先跑一下,然后找出关键字符串 关键字符串是You Get Wrong和Try Again,不过IDA好像识别不出来这个字符串,在Ollydbg中右键Search For,寻找所有字符串,可以找到这些字 ...

  2. Sql语句知识大全

    1.经典SQL语句大全(绝对的经典) 2. 3. 4.一.基础 1.1.说明:创建数据库 2.CREATE DATABASE database-name 3.2.说明:删除数据库 4.drop dat ...

  3. lamp :在Linux 下搭建apache、Mysql、php

    CentOS下搭建LAMP环境 LAMP: Linux + Apache + PHP + Mysql. 系统: CentOS 7,64位. CentOS安装 我选取了64位的CentOS 7这个Lin ...

  4. python 读取文件行

    将文件转化成二进制码,并读取行数,计算总行数 import os Str=input("请输入路径") Sum=0 def read(Str): a = os.listdir(St ...

  5. VisualStudio2015 安装

    环境:Win10 64位 推荐安装顺序 IIS > Sqlserver > Asp.Net 启动安装程序(出现Logo后需要等待1到2分钟),选择安装路径(注意不要出现中文路径) 勾选需求 ...

  6. java之JVM学习--简单理解编译和运行的过程之概览

    java代码编译流程图: java字节码执行由JVM执行引擎完成 Java代码编译和执行的整个过程包含了以下三个重要的机制: Java源码编译机制 类加载机制 类执行机制 Java源码编译机制 Jav ...

  7. S5PV210 点亮Led

    GPC1CON, R/W, Address = 0xE020_0080 GPC1DAT, R/W, Address = 0xE020_0084 举例 #define GPC1CON *((volati ...

  8. gradle安装教程

    https://blog.csdn.net/andwey/article/details/92800650 https://www.cnblogs.com/Jimc/p/10081605.html

  9. 为什么有了uwsgi还要nginx这个“前端”服务器

    相信每一个使用nginx+uwsgi+django部署过的人,都感到非常复杂.到底为什么一个项目的发布要经过这么多层级,他们每一层有什么理由存在?这就带大家宏观地看待一下 首先nginx 是对外的服务 ...

  10. 并发编程: 生产消费模型、死锁与Rlock、线程、守护线程、信号量、锁

    一.守护进程 二.互斥锁 三.抢票 四.进程间通讯 五.进程间通讯2 一.守护进程 """ 进程间通讯的另一种方式 使用queue queue 队列 队列的特点: 先进的 ...