Spring项目bean实例化

对象已经能交给SpringIOC容器来创建了,但是容器是如何来创建对象的呢?
就需要研究下bean的实例化过程,在这块内容中主要解决两部分内容,分别是

  • bean是如何创建的
  • 实例化bean的三种方式,构造方法,静态工厂实例工厂

在介绍这三种创建方式之前,我们需要先确认一件事:
bean本质上就是对象,对象在new的时候会使用构造方法完成,那创建bean也是使用构造方法完成的。
基于这点出发,我们来验证springbean的三种创建方式。

1. 环境准备

为了方便阅读代码,重新准备个开发环境,

  • 创建一个Maven项目
  • pom.xml添加依赖
  • resources下添加spring的配置文件applicationContext.xml

项目的结构如下:

在这里插入图片描述

2. 构造方法实例化

在上述的环境下,我们来研究下Spring中的第一种bean的创建方式构造方法实例化

步骤1:准备需要被创建的类

准备一个UserDaoUserDaoImpl

public interface UserDao {
    public void save();
}
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("User Dao save, running ......");
    }
}

步骤2:将类配置到Spring容器

<?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">

    <bean id="userDao" class="com.dcxuexi.dao.impl.UserDaoImpl" />

</beans>

步骤3:编写运行程序

public class SpringBeaInstance {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) context.getBean("userDao");
        userDao.save();

    }
}

步骤4:类中提供构造函数测试

UserDaoImpl类中添加一个无参构造函数,并打印一句话,方便观察结果。

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("User Dao save, running ......");
    }
    //无参构造函数
    public UserDaoImpl(){
        System.out.println("User Dao Impl constructor is running ......");
    }
}

运行程序,如果控制台有打印构造函数中的输出,说明Spring容器在创建对象的时候也走的是构造函数
在这里插入图片描述

步骤5:将构造函数改成private测试

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("User Dao save, running ......");
    }
    //无参构造函数
    private UserDaoImpl(){
        System.out.println("User Dao Impl constructor is running ......");
    }
}

运行程序,能执行成功,说明内部走的依然是构造函数,能访问到类中的私有构造方法,显而易见Spring底层用的是反射

在这里插入图片描述

步骤6:构造函数中添加一个参数测试

public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("User Dao save, running ......");
    }
    //无参构造函数
    private UserDaoImpl(String name){
        System.out.println("User Dao Impl constructor is running ......");
    }
}

运行程序,
程序会报错,说明Spring底层使用的是类的无参构造方法。
在这里插入图片描述

3. 分析Spring的错误信息

接下来,我们主要研究下Spring的报错信息来学一学如阅读。

  • 错误信息从下往上依次查看,因为上面的错误大都是对下面错误的一个包装,最核心错误是在最下面
  • Caused by: java.lang.NoSuchMethodException: com.dcxuexi.dao.impl.UserDaoImpl.<init>()
    • Caused by 翻译为引起,即出现错误的原因
    • java.lang.NoSuchMethodException:抛出的异常为没有这样的方法异常
    • com.dcxuexi.dao.impl.UserDaoImpl.<init>():哪个类的哪个方法没有被找到导致的异常,<init>()指定是类的构造方法,即该类的无参构造方法

如果最后一行错误获取不到错误信息,接下来查看第二层:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dcxuexi.dao.impl.UserDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.dcxuexi.dao.impl.UserDaoImpl.<init>()

  • nested:嵌套的意思,后面的异常内容和最底层的异常是一致的
  • Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dcxuexi.dao.impl.UserDaoImpl]: No default constructor found;
    • Caused by: 引发
    • BeanInstantiationException:翻译为bean实例化异常
    • No default constructor found:没有一个默认的构造函数被发现

看到这其实错误已经比较明显。
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dcxuexi.dao.impl.UserDaoImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.dcxuexi.dao.impl.UserDaoImpl.<init>()

至此,关于Spring的构造方法实例化就已经学习完了,因为每一个类默认都会提供一个无参构造函数,所以其实真正在使用这种方式的时候,我们什么也不需要做。这也是我们以后比较常用的一种方式。

4. 静态工厂实例化

接下来研究Spring中的第二种bean的创建方式静态工厂实例化

4.1 工厂方式创建bean

先回顾一个知识点是使用工厂来创建对象的方式:
(1)准备一个RegionDaoRegionDaoImpl

public interface RegionDao {
    public void select();
}
public class RegionDaoImpl implements RegionDao {
    public void select() {
        System.out.println("Region Dao running ......");
    }
}

(2)创建一个工厂类RegionDaoFactory并提供一个静态方法

//静态工厂创建对象
public class RegionDaoFactory {
    public static RegionDao getRegionDao(){
        return new RegionDaoImpl();
    }
}

(3)编写AppForInstanceRegion运行类,在类中通过工厂获取对象

public class AppForInstanceRegion {
    public static void main(String[] args) {
        // 通过静态工厂创建对象
        RegionDao regionDao = RegionDaoFactory.getRegionDao();
        regionDao.select();
    }
}

(4)运行后,可以查看到结果
在这里插入图片描述

如果代码中对象是通过上面的这种方式来创建的,如何将其交给Spring来管理呢?

4.2 静态工厂实例化

这就要用到Spring中的静态工厂实例化的知识了,具体实现步骤为:
(1)在spring的配置文件application.properties中添加以下内容:

<bean id="regionDao" class="com.dcxuexi.factory.RegionDaoFactory" factory-method="getRegionDao" />

class:工厂类的类全名
factory-mehod:具体工厂类中创建对象的方法名
对应关系如下图:

在这里插入图片描述

(2)在AppForInstanceRegion运行类,使用从IOC容器中获取bean的方法进行运行测试

public class AppForInstanceRegion {
    public static void main(String[] args) {
        // 通过静态工厂创建对象
        //RegionDao regionDao = RegionDaoFactory.getRegionDao();
        //regionDao.select();

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        RegionDao regionDao = (RegionDao) context.getBean("regionDao");
        regionDao.select();
    }
}

(3)运行后,可以查看到结果
在这里插入图片描述

可能有人会问了,你这种方式在工厂类中不也是直接new对象的,和我自己直接new没什么太大的区别,而且静态工厂的方式反而更复杂,这种方式的意义是什么?
主要的原因是:

  • 在工厂的静态方法中,我们除了new对象还可以做其他的一些业务操作,这些操作必不可少,如:
//静态工厂创建对象
public class RegionDaoFactory {
    public static RegionDao getRegionDao(){
        System.out.println("factory setup....");//模拟必要的业务操作
        return new RegionDaoImpl();
    }
}

之前new对象的方式就无法添加其他的业务内容,重新运行,查看结果:

在这里插入图片描述

介绍完静态工厂实例化后,这种方式一般是用来兼容早期的一些老系统,所以了解为主

5. 实例工厂与FactoryBean

接下来继续来研究Spring的第三种bean的创建方式实例工厂实例化

5.1 环境准备

(1)准备一个OrderDaoOrderDaoImpl

public interface OrderDao {
    public void save();
}
public class OrderDaoImpl implements OrderDao {
    public void save() {
        System.out.println("Order Dao save, running ......");
    }
}

(2)创建一个工厂类OrderDaoFactory并提供一个普通方法,注意此处和静态工厂的工厂类不一样的地方是方法不是静态方法

public class OrderDaoFactory {
    public OrderDao getOrderDao(){
        return new OrderDaoImpl();
    }
}

(3)编写AppForInstanceOrder运行类,在类中通过工厂获取对象

public class AppForInstanceOrder {
    public static void main(String[] args) {
        //创建实例工厂对象
        OrderDaoFactory orderDaoFactory = new OrderDaoFactory();
        //通过实例工厂对象创建对象
        OrderDao orderDao = orderDaoFactory.getOrderDao();
        orderDao.save();
    }
}

(4)运行后,可以查看到结果

在这里插入图片描述

对于上面这种实例工厂的方式如何交给Spring管理呢?

5.2 实例工厂实例化

具体实现步骤为:
(1)在spring的配置文件中添加以下内容:

<bean id="orderDaoFactory" class="com.dcxuexi.factory.OrderDaoFactory" />
<bean id="orderDao" factory-method="getOrderDao" factory-bean="orderDaoFactory" />

实例化工厂运行的顺序是:

  • 创建实例化工厂对象,对应的是第一行配置
  • 调用对象中的方法来创建bean,对应的是第二行配置
    • factory-bean:工厂的实例对象
    • factory-method:工厂对象中的具体创建对象的方法名,对应关系如下:

在这里插入图片描述

factory-mehod:具体工厂类中创建对象的方法名
(2)在AppForInstanceOrder运行类,使用从IOC容器中获取bean的方法进行运行测试

public class AppForInstanceOrder {
    public static void main(String[] args) {
        //创建实例工厂对象
        //OrderDaoFactory orderDaoFactory = new OrderDaoFactory();
        //通过实例工厂对象创建对象
        //OrderDao orderDao = orderDaoFactory.getOrderDao();
        //orderDao.save();

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderDao orderDao = (OrderDao) context.getBean("orderDao");
        orderDao.save();
    }
}

(3)运行后,可以查看到结果
在这里插入图片描述

实例工厂实例化的方式就已经介绍完了,配置的过程还是比较复杂,所以Spring为了简化这种配置方式就提供了一种叫FactoryBean的方式来简化开发。

5.3 FactoryBean的使用

具体的使用步骤为:
(1)创建一个UserDaoFactoryBean的类,实现FactoryBean接口,重写接口的方法

public class UserDaoFactoryBean implements FactoryBean<UserDao> {
    //代替原始实例工厂中的创建对象的方法
    public UserDao getObject() throws Exception {
        return new UserDaoImpl();
    }

    //返回所创建类的class对象
    public Class<?> getObjectType() {
        return UserDao.class;
    }
}

(2)在Spring的配置文件中进行配置

<bean id="userDao" class="com.dcxuexi.factory.UserDaoFactoryBean" />

(3)AppForInstanceUser运行类,直接运行
在这里插入图片描述

这种方式在Spring去整合其他框架的时候会被用到,所以这种方式需要大家理解掌握。
查看源码会发现,FactoryBean接口其实会有三个方法,分别是:

public interface FactoryBean<T> {
    String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";

    @Nullable
    T getObject() throws Exception;

    @Nullable
    Class<?> getObjectType();

    default boolean isSingleton() {
        return true;
    }
}

方法一getObject(),被重写后,在方法中进行对象的创建并返回
方法二getObjectType(),被重写后,主要返回的是被创建类的Class对象
方法三:没有被重写,因为它已经给了默认值,从方法名中可以看出其作用是设置对象是否为单例,默认true,从意思上来看,我们猜想默认应该是单例,如何来验证呢?

思路很简单,就是从容器中获取该对象的多个值,打印到控制台,查看是否为同一个对象。

public class AppForInstanceUser {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao) context.getBean("userDao");
        UserDao userDao2 = (UserDao) context.getBean("userDao");
        userDao.save();
        userDao2.save();
        System.out.println(userDao);
        System.out.println(userDao2);

    }
}

打印结果,如下:

在这里插入图片描述

从结果中可以看出现在已经是非单例了,但是一般情况下我们都会采用单例,也就是采用默认即可。所以isSingleton()方法一般不需要进行重写。

6. bean实例化小结

(1)bean是如何创建的呢?

构造方法

(2)SpringIOC实例化对象的三种方式分别是:

  • 构造方法(常用)
  • 静态工厂(了解)
  • 实例工厂(了解)
    • FactoryBean(实用)

这些方式中,重点掌握构造方法FactoryBean即可。
需要注意的一点是,构造方法在类中默认会提供,但是如果重写了构造方法,默认的就会消失,在使用的过程中需要注意,如果需要重写构造方法,最好把默认的构造方法也重写下。


项目代码

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.D.Chuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值