3、基于XML管理bean

文章目录


【尚硅谷】SSM框架全套教程-讲师:杨博超

但行好事,莫问前程

3、基于XML管理bean

实验一:入门案例

1 创建Maven Module

2 引入依赖

<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.22</version>
</dependency>
<!-- junit测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

在这里插入图片描述

3 创建类HelloWorld

public class HelloWorld {

    public void sayHello() {
        System.out.println("HelloWorld");
    }
}

4 创建Spring的配置文件

在这里插入图片描述

5 在Spring的配置文件中配置bean

<?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">
    
	<!--
	配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
	通过bean标签配置IOC容器所管理的bean
	属性:
		id:设置bean的唯一标识
		class:设置bean所对应类型的全类名
	-->
    <bean id="helloWorld" class="pers.tianyu.bean.HelloWorld"></bean>
</beans>

6 创建测试类测试

@Test
public void testSayHelloById(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld bean = (HelloWorld) context.getBean("helloWorld");
    bean.sayHello();
}

7 思路

在这里插入图片描述

8 注意

Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。

如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of bean
failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nested
exception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld.<init>
()

实验二:获取bean

1 方式一:根据id获取

由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。

上个实验中我们使用的就是这种方式。

2 方式二:根据类型获取

@Test
public void testSayHelloByType(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld bean = context.getBean(HelloWorld.class);
    bean.sayHello();
}

3 方式三:根据id和类型

@Test
public void testSayHelloByIdByType(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    HelloWorld bean = context.getBean("helloWorld", HelloWorld.class);
    bean.sayHello();
}

4 注意

当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个

当IOC容器中一共配置了两个:

<bean id="helloWorldOne" class="pers.tianyu.bean.HelloWorld"></bean>
<bean id="helloWorldTwo" class="pers.tianyu.bean.HelloWorld"></bean>

根据类型获取时会抛出异常:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean
of type 'com.atguigu.spring.bean.HelloWorld' available: expected single matching bean but
found 2: helloworldOne,helloworldTwo

5 扩展

如果组件类实现了接口,根据接口类型可以获取 bean 吗?

可以,前提是bean唯一

@Test
public void testBImplA(){
    // A:接口 有一个方法sayA待实现
    // B:实现类 实现接口A,并在spring的XML文件中配置bean
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 在获取类型时写A.class
    A b = context.getBean(A.class);
    b.sayA();
}

如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?

不行,因为bean不唯一

@Test
public void testBImplAC(){
    // A:接口 有一个方法sayA待实现
    // B:实现类 实现接口A,并在spring的XML文件中配置bean
    // C:实现类 实现接口A,并在spring的XML文件中配置bean
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 在获取类型时写A.class
    A b = context.getBean(A.class);
    b.sayA(); // 报错,如果加id就不报错
}

6 结论

根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

实验三:依赖注入之setter注入

1 创建学生类Student

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    
    // 无参有参构造函数
    // setget方法
    // toString方法
}

2 配置bean时为属性赋值

<bean id="studentSet" class="pers.tianyu.bean.Student">
    <property name="id" value="1001"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="23"></property>
    <property name="sex" value=""></property>
</bean>

3 测试

@Test
public void testDIBySet() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Student bean = context.getBean("studentSet",Student.class);
    System.out.println(bean);
}

实验四:依赖注入之构造器注入

1 在Student类中添加有参构造

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    
    // 无参有参构造函数
    // setget方法
    // toString方法
}

2 配置bean

<bean id="studentConstructor" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
</bean>

注意

  • constructor-arg标签还有两个属性可以进一步描述构造器参数:
    • index属性:指定参数所在位置的索引(从0开始)
    • name属性:指定参数名

3 测试

@Test
public void testDIBySet() {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Student bean = context.getBean("studentConstructor",Student.class);
    System.out.println(bean);
}

实验五:特殊值处理

1 字面量赋值

什么是字面量?

int a = 10;

声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。

当我们引用a的时候,我们实际上拿到的值是10。

而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。

所以字面量没有引申含义,就是我们看到的这个数据本身。

<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>

2 null值

<property name="name">
	<null />
</property>

注意

<property name="name" value="null"></property>

以上写法,为name所赋的值是字符串’null’

3 xml实体

实体是对数据的引用,根据实体种类的不同,XML 解析器将使用实体的替代文本或者外部文档的内容来替代实体引用。

  • 介绍以下几种常用实体
    • &apos; 是一个撇号:’
    • &amp; 是一个与字符:&
    • &quot; 是一个引号:"
    • &lt; 是一个小于号:<
    • &gt; 是一个大于号:>
<!-- 如果想写<王五>,大于、小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="name" value="&lt;王五&gt;"/>

4 CDATA节

<property name="name">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<!-- idea快捷键CD -->
<value><![CDATA[ <王五> ]></value>
</property>

实验六:类(类型)属性赋值

1 创建班级类Clazz

public class Clazz {
    private Integer clazzId;
    private String ClassName;

    // 无参有参构造函数
    // setget方法
    // toString方法
}

2 修改Student类

在Student类中添加Clazz类型,并添加set、get方法。

private Clazz clazz;

public Clazz getClazz() {
	return clazz;
}
public void setClazz(Clazz clazz) {
	this.clazz = clazz;
}

3 方式一:引用外部已声明的bean

配置Clazz类型的bean

<bean id="clazzOne" class="pers.tianyu.bean.Clazz">
    <property name="clazzId" value="1904"></property>
    <property name="className" value="1904班"></property>
</bean>

为Student中的clazz属性赋值

<bean id="studentOne" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz" ref="clazzOne"></property>
</bean>

错误演示

<bean id="studentOne" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz" value="clazzOne"></property>
</bean>

如果错把ref属性写成了value属性,会抛出异常:
Caused by: java.lang.IllegalStateException:Cannot convert value of type ‘java.lang.String’ to required type ‘com.atguigu.spring.bean.Clazz’ for property ‘clazz’: no matching editors or conversionstrategy found

意思是不能把String类型转换成我们要的Clazz类型,说明我们使用value属性时,Spring只把这个属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值。

4 方式二:内部bean

<bean id="studentOne" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
    <!-- 在一个bean中再声明一个bean就是内部bean -->
	<!-- 内部bean只能用于给属性赋值,不能在外部通过IOC容器获取,因此可以省略id属性 -->
    <property name="clazz">
        <bean name="clazzInner" class="pers.tianyu.bean.Clazz">
            <property name="clazzId" value="1908"></property>
            <property name="className" value="1908班"></property>
        </bean>
    </property>
</bean>

5 方式三:级联属性赋值

<bean id="studentOne" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
    <!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="clazz.clazzId" value="2222"></property>
    <property name="clazz.className" value="2222班"></property>
</bean>

实验七:数组(类型)属性赋值

1 修改Student类

添加数组类型属性,添加set、get方法。

private String[] hobbies;

public String[] getHobbies() {
	return hobbies;
}
public void setHobbies(String[] hobbies) {
	this.hobbies = hobbies;
}

2 配置bean

<bean id="studentOne" class="pers.tianyu.bean.Student">
    <constructor-arg value="1003"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="30"></constructor-arg>
    <constructor-arg value=""></constructor-arg>
    <!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
    <property name="clazz" ref="clazzOne"></property>
    <property name="hobbies" >
        <array>
            <value>抽烟</value>
            <value>喝酒</value>
            <value>烫头</value>
        </array>
    </property>
</bean>

实验八:集合(类型)属性赋值

1 List集合类型属性赋值

在Clazz类中添加集合类型属性,添加set、get方法。

private List<Student> students;

public List<Student> getStudents() {
	return students;
}
public void setStudents(List<Student> students) {
	this.students = students;
}

配置bean

<bean id="clazzOne" class="pers.tianyu.bean.Clazz">
    <property name="clazzId" value="1904"></property>
    <property name="className" value="1904班"></property>
    <property name="students">
        <list>
            <ref bean="studentOne"></ref>
        </list>
    </property>
</bean>

注意

若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可

2 Map集合类型属性赋值

创建教师类Teacher

public class Teacher {
    private Integer teacherId;
    private String teacherName;
    // 有参无参构造函数
    // setget方法
    // toString方法
}

在Student类中添加map类型属性,添加set、get方法。

private Map<String, Teacher> teacherMap;

public Map<String, Teacher> getTeacherMap() {
	return teacherMap;
}

public void setTeacherMap(Map<String, Teacher> teacherMap) {
	this.teacherMap = teacherMap;
}

配置bean

<bean id="thacherOne" class="pers.tianyu.bean.Teacher">
    <property name="teacherId" value="1001"></property>
    <property name="teacherName" value="深田永美"></property>
</bean>
<bean id="thacherTwo" class="pers.tianyu.bean.Teacher">
    <property name="teacherId" value="1002"></property>
    <property name="teacherName" value="周淑怡"></property>
</bean>
<bean id="studentThree" class="pers.tianyu.bean.Student">
    <property name="id" value="1004"></property>
    <property name="name" value="王五"></property>
    <property name="age" value="26"></property>
    <property name="sex" value=""></property>
    <property name="hobbies">
        <list>
            <value>抽烟</value>
            <value>喝酒</value>
            <value>烫头</value>
        </list>
    </property>
    <property name="teacherMap">
        <map>
            <entry>
                <key><value>1001</value></key>
                <ref bean="thacherOne"></ref>
            </entry>
            <entry>
                <key><value>1002</value></key>
                <ref bean="thacherTwo"></ref>
            </entry>
        </map>
    </property>
</bean>

3 引用集合类型的bean

在bean中property标签写ref引用id即可。

<!--list集合类型的bean-->
<util:list id="students">
    <ref bean="studentOne"></ref>
    <ref bean="studentThree"></ref>
</util:list>

<!--map集合类型的bean-->
<util:map id="teacherMap">
    <entry>
        <key> <value>1001</value></key>
        <ref bean="thacherOne"></ref>
    </entry>
    <entry>
        <key><value>1002</value></key>
        <ref bean="thacherTwo"></ref>
    </entry>
</util:map>

注意

使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择

实验九:p命名空间

引入p命名空间后,可以通过以下方式为bean的各个属性赋值

set方法注入

<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<!--xmlns:p="http://www.springframework.org/schema/p" -->
<bean id="teacherThree" class="pers.tianyu.pojo.Teacher"
      p:teacherId="1003" p:teacherName="三上悠亚">
</bean>

实验十:c命名空间

构造器注入

<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<!--xmlns:c="http://www.springframework.org/schema/c"-->
<bean id="teacherFour" class="pers.tianyu.pojo.Teacher"
      c:teacherId="1004" c:teacherName="饭岛爱">
</bean>

注意

必须有有参构造、set方法,缺一不可。

实验十一:引入外部属性文件

1 加入依赖

<!-- MySQL驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.16</version>
</dependency>
<!-- 数据源 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.31</version>
</dependency>

2 创建外部属性文件

jdbc.properties

在这里插入图片描述

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root

3 引入属性文件

<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

4 配置bean

<!--配置Druid数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

5 测试

@Test
public void testDataSource() throws SQLException {
	ApplicationContext ac = new ClassPathXmlApplicationContext("springdatasource.xml");
	DataSource dataSource = ac.getBean(DataSource.class);
	Connection connection = dataSource.getConnection();
	System.out.println(connection);
}

实验十二:bean的作用域

1 概念

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:

取值含义创建对象的时机
singleton(默认)在IOC容器中,这个bean的对象始终为单实例IOC容器初始化时
prototype这个bean在IOC容器中有多个实例获取bean时

如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):

取值含义
request在一个请求范围内有效
session在一个会话范围内有效

2 创建类User

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
	// 有参无参构造方法
	// setget方法
	// toString方法
}

3 配置bean

<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建
对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean id="User" class="pers.tianyu.pojo.User" scope="singleton">
    <property name="id" value="1001"></property>
    <property name="username" value="张三"></property>
</bean>

4 测试

@Test
public void test03() {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
    User user1 = context.getBean(User.class);
    User user2 = context.getBean(User.class);
    System.out.println(user1 == user2);
}

实验十三:bean的生命周期

1 具体的生命周期过程

  • bean对象创建(调用无参构造器)
  • 给bean对象设置属性
  • bean对象初始化之前操作(由bean的后值处理器中前置方法负责)
  • bean对象初始化(需在配置bean时指定初始化方法)
  • bean对象初始化之后操作(由bean的后置处理器后置方法负责)
  • bean对象就绪可以使用
  • bean对象销毁(需在配置bean时指定销毁方法)
  • IOC容器关闭

2 修改类User

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;

    public User() {
        System.out.println("生命周期:1、创建对象");
    }

    public User(Integer id, String username, String password, Integer age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }
    public void initMethod(){
        System.out.println("生命周期:3、初始化");
    }
    public void destroyMethod(){
        System.out.println("生命周期:5、销毁");
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        System.out.println("生命周期:2、依赖注入");
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

注意

其中的initMethod()destroyMethod(),可以通过配置bean指定为初始化和销毁的方法

3 配置bean

<bean id="User" class="pers.tianyu.bean.User" init-method="initMethod" destroy-method="destroyMethod">
    <property name="id" value="1001"></property>
    <property name="username" value="张三"></property>
</bean>

4 测试

@Test
public void test04(){
    // 不能使用ApplicationContext,它没有close()方法
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
    User bean = context.getBean(User.class);
    System.out.println(bean);
    context.close();
}

5 bean的后置处理器

bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行

创建bean的后置处理器:

public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 此方法在bean的生命周期初始化之前执行
        System.out.println("生命周期:4、前置");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 此方法在bean的生命周期初始化之后执行
        System.out.println("生命周期:4、后置");
        return bean;
    }
}

在IOC容器中配置后置处理器:

<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="beanPostProcessor" class="pers.tianyu.process.MyBeanPostProcessor"></bean>

在这里插入图片描述

实验十四:FactoryBean

1 简介

FactoryBean是Spring提供的一种整合第三方框架的常用机制。

与普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。

通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。

将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。

/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by objects used within a {@link BeanFactory}
which
* are themselves factories for individual objects. If a bean implements this
* interface, it is used as a factory for an object to expose, not directly as a
* bean instance that will be exposed itself.
*
* <p><b>NB: A bean that implements this interface cannot be used as a normal
bean.</b>
* A FactoryBean is defined in a bean style, but the object exposed for bean
* references ({@link #getObject()}) is always the object that it creates.
*
* <p>FactoryBeans can support singletons and prototypes, and can either create
* objects lazily on demand or eagerly on startup. The {@link SmartFactoryBean}
* interface allows for exposing more fine-grained behavioral metadata.
*
* <p>This interface is heavily used within the framework itself, for example
for
* the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} or the
* {@link org.springframework.jndi.JndiObjectFactoryBean}. It can be used for
* custom components as well; however, this is only common for infrastructure
code.
*
* <p><b>{@code FactoryBean} is a programmatic contract. Implementations are not
* supposed to rely on annotation-driven injection or other reflective
facilities.</b>
* {@link #getObjectType()} {@link #getObject()} invocations may arrive early in
the
* bootstrap process, even ahead of any post-processor setup. If you need access
to
* other beans, implement {@link BeanFactoryAware} and obtain them
programmatically.
*
* <p><b>The container is only responsible for managing the lifecycle of the
FactoryBean
* instance, not the lifecycle of the objects created by the FactoryBean.</b>
Therefore,
* a destroy method on an exposed bean object (such as {@link
java.io.Closeable#close()}
* will <i>not</i> be called automatically. Instead, a FactoryBean should
implement
* {@link DisposableBean} and delegate any such close call to the underlying
object.
*
* <p>Finally, FactoryBean objects participate in the containing BeanFactory's
* synchronization of bean creation. There is usually no need for internal
* synchronization other than for purposes of lazy initialization within the
* FactoryBean itself (or the like).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 08.03.2003
* @param <T> the bean type
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.aop.framework.ProxyFactoryBean
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public interface FactoryBean<T> {
	/**
	* The name of an attribute that can be
	* {@link org.springframework.core.AttributeAccessor#setAttribute set} on a
	* {@link org.springframework.beans.factory.config.BeanDefinition} so that
	* factory beans can signal their object type when it can't be deduced from
	* the factory bean class.
	* @since 5.2
	*/
	String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
	/**
	* Return an instance (possibly shared or independent) of the object
	* managed by this factory.
	* <p>As with a {@link BeanFactory}, this allows support for both the
	* Singleton and Prototype design pattern.
	* <p>If this FactoryBean is not fully initialized yet at the time of
	* the call (for example because it is involved in a circular reference),
	* throw a corresponding {@link FactoryBeanNotInitializedException}.
	* <p>As of Spring 2.0, FactoryBeans are allowed to return {@code null}
	* objects. The factory will consider this as normal value to be used; it
	* will not throw a FactoryBeanNotInitializedException in this case anymore.
	* FactoryBean implementations are encouraged to throw
	* FactoryBeanNotInitializedException themselves now, as appropriate.
	* @return an instance of the bean (can be {@code null})
	* @throws Exception in case of creation errors
	* @see FactoryBeanNotInitializedException
	*/
	@Nullable
	T getObject() throws Exception;
	/**
	* Return the type of object that this FactoryBean creates,
	* or {@code null} if not known in advance.
	* <p>This allows one to check for specific types of beans without
	* instantiating objects, for example on autowiring.
	* <p>In the case of implementations that are creating a singleton object,
	* this method should try to avoid singleton creation as far as possible;
	* it should rather estimate the type in advance.
	* * For prototypes, returning a meaningful type here is advisable too.
	* <p>This method can be called <i>before</i> this FactoryBean has
	* been fully initialized. It must not rely on state created during
	* initialization; of course, it can still use such state if available.
	* <p><b>NOTE:</b> Autowiring will simply ignore FactoryBeans that return
	* {@code null} here. Therefore it is highly recommended to implement
	* this method properly, using the current state of the FactoryBean.
	* @return the type of object that this FactoryBean creates,
	* or {@code null} if not known at the time of the call
	* @see ListableBeanFactory#getBeansOfType
	*/
	@Nullable
	Class<?> getObjectType();
	/**
	* Is the object managed by this factory a singleton? That is,
	* will {@link #getObject()} always return the same object
	* (a reference that can be cached)?
	* <p><b>NOTE:</b> If a FactoryBean indicates to hold a singleton object,
	* the object returned from {@code getObject()} might get cached
	* by the owning BeanFactory. Hence, do not return {@code true}
	* unless the FactoryBean always exposes the same reference.
	* <p>The singleton status of the FactoryBean itself will generally
	* be provided by the owning BeanFactory; usually, it has to be
	* defined as singleton there.
	* <p><b>NOTE:</b> This method returning {@code false} does not
	* necessarily indicate that returned objects are independent instances.
	* An implementation of the extended {@link SmartFactoryBean} interface
	* may explicitly indicate independent instances through its
	* {@link SmartFactoryBean#isPrototype()} method. Plain {@link FactoryBean}
	* implementations which do not implement this extended interface are
	* simply assumed to always return independent instances if the
	* {@code isSingleton()} implementation returns {@code false}.
	* <p>The default implementation returns {@code true}, since a
	* {@code FactoryBean} typically manages a singleton instance.
	* @return whether the exposed object is a singleton
	* @see #getObject()
	* @see SmartFactoryBean#isPrototype()
	*/
	default boolean isSingleton() {
		return true;
	}
}

2 创建类UserFactoryBean

getObject():通过一个对象交给IOC容器管理
getObjectType():设置所提供对象的类型
isSingleton():所提供对象是否单例

public class UserFactoryBean implements FactoryBean<User> {

    @Override
    public User getObject() throws Exception {
        return new User();
    }

    @Override
    public Class<?> getObjectType() {
        return User.class;
    }
}

3 配置bean

<bean class="pers.tianyu.Factory.UserFactoryBean"/>

4 测试

@Test
public void test05(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-scope.xml");
    User bean = context.getBean(User.class);
    System.out.println(bean);
}

在这里插入图片描述

实验十五:基于xml的自动装配

自动装配:

根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值

1 场景模拟

创建类UserController

public class UserController {
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void saveUser() {
        userService.saveUser();
    }
}

创建接口UserService

public interface UserService {
    void saveUser();
}

创建类UserServiceImpl实现接口UserService

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void saveUser() {
        userDao.saveUser();
    }
}

创建接口UserDao

public interface UserDao {
    void saveUser();
}

创建类UserDaoImpl实现接口UserDao

public class UserDaoImpl implements UserDao {
    @Override
    public void saveUser() {
        System.out.println("保存成功");
    }
}

2 配置bean

使用bean标签的autowire属性设置自动装配效果

自动装配方式:byType

byType:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException

<bean id="controller" class="pers.tianyu.controller.UserController" autowire="byType"></bean>
<bean id="service" class="pers.tianyu.service.impl.UserServiceImpl" autowire="byType"></bean>
<bean id="dao" class="pers.tianyu.dao.impl.UserDaoImpl"></bean>

自动装配方式:byName

byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值

<bean id="controller" class="pers.tianyu.controller.UserController" autowire="byName"></bean>
<bean id="userService" class="pers.tianyu.service.impl.UserServiceImpl" autowire="byName"></bean>
<bean id="userDao" class="pers.tianyu.dao.impl.UserDaoImpl"></bean>

3 测试

@Test
public void test06() {
    ApplicationContext context = new ClassPathXmlApplicationContext("autowrite.xml");
    UserController bean = context.getBean(UserController.class);
    bean.saveUser();
}
Spring框架是一种轻量级的Java开发框架,主要使用依赖注入和面向切面编程等技术来完成应用程序的开发和管理。在Spring框架中,注入Bean是非常重要的一个概念。在XML配置文件中,可以使用以下几种方式来注入Bean: 1. Constructor注入 使用Constructor注入是指在Bean实例化时,通过构造函数(Constructor)注入需要的依赖。在配置文件中使用 <constructor-arg> 标签来配置参数,例如: <bean id="foo" class="com.example.Foo"> <constructor-arg index="0" value="fooValue"/> <constructor-arg index="1" value="barValue"/> </bean> 2. Setter注入 使用Setter注入是指在Bean实例化后,通过Setter方法注入需要的依赖。在配置文件中使用 <property> 标签来配置参数,例如: <bean id="foo" class="com.example.Foo"> <property name="foo" value="fooValue" /> <property name="bar" value="barValue" /> </bean> 3. 静态工厂方法注入 使用静态工厂方法注入是指通过静态工厂方法(static factory method)来实例化Bean,并注入需要的依赖。在配置文件中使用 <bean> 标签的 factory-method 属性来指定工厂方法名称,例如: <bean id="foo" class="com.example.Foo" factory-method="createFoo"> <constructor-arg index="0" value="fooValue"/> <constructor-arg index="1" value="barValue"/> </bean> 4. 实例化工厂方法注入 使用实例化工厂方法注入是指在Bean实例化前,通过实例化工厂方法(factory method)来实例化Bean,并注入需要的依赖。在配置文件中使用 <bean> 标签的 factory-bean 和 factory-method 属性来指定工厂Bean和工厂方法名称,例如: <bean id="fooFactory" class="com.example.FooFactory"/> <bean id="foo" factory-bean="fooFactory" factory-method="createFoo"> <constructor-arg index="0" value="fooValue"/> <constructor-arg index="1" value="barValue"/> </bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值