Spring框架——Bean与DI

Bean

一个Spring IoC容器管理了一个或者多个beans
这些beans通过你提供给容器的配置元数据进行创建

Bean的实例化

1. 通过构造方法实例化

xml配置bean,调用空的构造方法。

<bean id="IntelCpu" class="com.pc.IntelCpu"></bean>

2. 使用静态工厂方法实例化

  • factory-method=“静态方法名”
  • class=“类名目录”

xml文件

<bean id="IntelCpu" class="com.pc.IntelCpu" factory-method="静态方法名"></bean>

//通过静态工厂实例化Bean
public static Computer 静态方法命() {
      System.out.println("静态工厂构建Bean");
      return new Computer();
}

3. 使用实例工厂实例化

  • factory-bean=“包含工厂方法的bean名称”
  • factory-method=“bean工厂方法”
  • class属性为空

//新建一个类
//类中创建Bean类对象

xml

<bean id="ThinkPad" class="com.pc.ThinkPad"></bean>
<bean id="Computer" factory-bean="ThinkPad" factory-method="createComputer">
      <property name="cpu" ref="IntelCpu"></property>
</bean>

Bean的生命周期

  1. 实例化
  2. 设置属性
  3. 设置Bean名称、Bean工厂、应用上下文[可实现]
    • 接口BeanNameAware 方法setBeanName()
    • 接口BeanFactoryAware 方法setBeanFactory
    • 接口ApplicationContextAware 方法setApplicationContext
  4. 初始化前预处理
  5. 初始化Bean
    • 实现InitializingBean接口的afterPropertiesSet()方法
    • 声明了初始化方法,将调用声明的
  6. 初始化后预处理
  7. Bean准备好
    • 单例模式
  8. 销毁Bean
    • 实现DisposableBean接口的destroy()方法
    • 声明了销毁方法,将调用声明的

Bean的初始化和销毁方法

1. 实现InitializingBean接口、DisposableBean接口

  • 简单、Bean实现和Spring框架耦合
  • 不推荐,类中融入了Spring的代码

2. 在bean配置文件配置init-methoddestroy-method方法

在类文件中定义方法

public void init() {
      System.out.println("init");
}
	
public void destroy() {
      System.out.println("destroy");
}

xml

<bean id="Student" class="com.pc.Student" init-method="init" destroy-method="destroy">
      <property name="name" value="zhangsan"></property>
</bean>	

测试类关闭容器

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu = (Student)ctx.getBean("Student");
stu.show();
ctx.close();

3. 注解@PostConstruct@PreDestory

xml

<context:annotation-config></context:annotation-config>
<context:component-scan base-package="包名"></context:component-scan>

java

//@Component("类名")
//@Value("值")
//@PostConstruct  初始化方法
//@PreDestory  销毁方法

Bean作用域

作用域 描述
singleton 一个Bean对应一个对象实例
prototype 一个Bean对应多个对象实例
request 一个Bean定义作用于request周期
session session周期
application application周期
global session 全局session周期

注意

1.(singleton)单例作用域是针对一个Spring容器一个实例、是Spring中Bean的默认作用域
2. Spring不管理原型作用域的完整生命周期,只负责初始化、配置、组装。不调用Bean的销毁方法。

依赖注入

注入方式

Spring支持DI的两种注入方式

1. 构造器注入

  • 有参的构造方法
  • 在配置文件内,<constructor-arg name=" " value=" "></constructor-arg>
  • 参数顺序[xml配置]
    • 类型:type="String"
    • 索引:index="0"
    • 名字:name="num1" 
  • 引用注入

类定义有参构造方法

public MathUtil(String num1, int num2) {
      this.num1 = num1;
      this.num2 = num2;
}

xml文件配置

	<!--构造器注入 -->
        <!--双参构造-->
	<bean id="id名" class="包名">
		<constructor-arg name="num2" value="20"></constructor-arg>
		<constructor-arg name="num1" value="abc"></constructor-arg>
	</bean>

2. Setter方法注入

  • 类中需要有set方法
  • xml配置文件中 name 与类中命名一致

Setter注入分类

  1. 基本数据类型注入
    • <property name=" " value=" ">
    • 字符串、数值型数据、布尔类型
  2. NULL注入
    • <property name=" "> <null /> </property>
  3. 引用数据类型注入
    • 引用
      • <property name=" " ref=" "/>
      • <property name=" "><ref bean=" "/></property>
    • 内部Bean
      • <property name=" "> <bean class=" "> </property>
      • 内部Bean不能重复使用,只能被注入
  4. List类型和数组类型
<property name=" ">
      <list>
            <ref bean=" "/>
            <value>A</value>
      </list>
</property>
  1. Set类型(保证每一个元素都是唯一的)
<property name = "">
      <set>
            <value>a</value>
            <value>b</value>
      </set>
</property>
  1. Map类型
<property name=“xxx”>
      <map>
            <entry key="" value=""></entry>
            <entry key=“a” value-ref=“aa” />
            <entry key=“b” value-ref=“bb” />
      </map>
</property>
  1. Properties 
    • 键值都是字符串类型
<property name="">
      <props>
            <prop key="a">abc</prop>
      </props>
</property>

高级Bean注入

Spring容器可以自动装配互相协作Bean的关联关系

类型

Mode 解释
no 不自动装配
byName 通过属性名称自动装配
byType 通过属性类型相同自动装配
constructor 参数

xml修改

<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-4.0.xsd
		            http://www.springframework.org/schema/context 
                            http://www.springframework.org/schema/context/spring-context-4.0.xsd"
	default-autowire="byType">
</beans>

优势

  • 自动装配可以显著的减少指定属性或者构造器参数的需求
  • 当对象发生变化时自动装配可以更新配置而不需要修改配置

局限

  • Propertyconstructor-arg显示的依赖设置会覆盖自动装配
  • 自动装配没有显示编写明确
  • 在容器中可能存在多个bean的定义与自动装配的setter方法或者构造方法参数匹配。若bean定义不唯一,装配时会抛异常

模板装配

声明父类Bean和子类Bean

用法

  • 指定abstract=“true”
    • bean时抽象的,不能实例化
    • 可做模板,抽象共同属性  
  • 指定parent,parent=“id”
    • 可继承父Bean属性,和类
    • 覆盖继承的属性

从外部资源文件获得数据

  1. xx.properties
  2. 键值对存储
db.user.name=lc

用法

<!--单个文件-->
<context:property-placeholder location="xx.properties"/>
<!--多个文件-->
<context:property-placeholder location="*.properties"/>


<!--注入-->
<property name="" value="${db.user.name}"></property>
posted @ 2020-08-25 10:16  不爱学习的小策  阅读(221)  评论(0编辑  收藏  举报