本文知识点(目录):

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. python-day3(正式学习)

    执行python的两种方式 交互式 优点:运行一句执行一句,方便修改 缺点:关闭即消失,无法保存 命令行式 优点:能一直保存 缺点:代码全部写完才可以调试bug 以后尽量使用pycharm和jupyt ...

  2. 洛谷P1087 FBI树

    P1087 FBI树题解: 看到这个题,我想到了线段树!(毕竟刚搞完st表...) 当然,题解中有位大佬也用的线段树,但是当时看的时候我看见了9个if,当场去世. 那么这是一个不用暴力的线段树,且简单 ...

  3. k8s之RBAC-基于角色的访问控制

    一个在名称空间内的对象的完整url模板: Object_URL: /apis/<GROUP>/<VERSION>/namespaces/<NAMESPACE_NAME&g ...

  4. jemeter鬓发压力测试包

    使用: 为子线程添加响应时间:https://www.cnblogs.com/duanxz/p/5464993.html 结果查看分析:聚合报告在监听器里面: https://wenku.baidu. ...

  5. Linux I2C核心、总线和设备驱动

    目录 更新记录 一.Linux I2C 体系结构 1.1 Linux I2C 体系结构的组成部分 1.2 内核源码文件 1.3 重要的数据结构 二.Linux I2C 核心 2.1 流程 2.2 主要 ...

  6. mycat sql timeout 问题解决

    发现程序中有个批量update语句需要update 16000多条数据导致超时 2019-11-06 10:35:28.312 pool-9-thread-24 ERROR com.hp.nova.c ...

  7. css选择器找亲戚

    1.first-child first-child表示选择列表中的第一个标签.代码如下: li:first-child{background:#090} 上面的意思是,li 列表中的 第一个li模块的 ...

  8. 微信小程序编译提示tabar.iconPath 文件不存在

    tabBar.list[0].iconPath 文件不存在 明明是按路径放了本地图片的,却依然显示路径不存在 需要把路径的图片转移到编译后的weapp文件中相同路径下的img文件中 本地正常路径 粘贴 ...

  9. 不怕你配置不会,就怕你看的资料不对!MIM 与 SharePoint 同步完全配置指南。

    为了更好的同步 User Profile,在 SharePoint 2010 中首次引入了 FIM (ForeFront Identity Manager) 用于编辑 User Profile 的同期 ...

  10. liunx pyinotify的安装和使用

    介绍此功能是检测目录的操作的事件 1.安装 在百度云盘下载或者在gits上下载安装包 链接:https://pan.baidu.com/s/1Lqt872YEgEo_bNPEnEJMaw 提取码:bj ...