Spring中的工厂类、bean的作用范围和生命周期

1.Spring中的工厂类

1.1ApplicationContext

  • ClassPathXmlApplicationContext:加载类路径下 Spring 的配置文件

  • FileSystemXmlApplicationContext:加载本地磁盘下 Spring 的配置文件

1.1.1service

ApplicationContext:只要一读取配置文件,默认情况下就会创建对象。

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public UserServiceImpl(UserDao userDao, String msg) {
        this.userDao = userDao;
        this.msg = msg;
    }

    @Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

1.1.2applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl" autowire="byType">
    </bean>



</beans>

1.1.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) {
 /**
         * 测试BeanFactory和ApplicationContext的区别
         */
        new ClassPathXmlApplicationContext("applicationContext.xml");
        //XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
      //  UserService userService = xbf.getBean("userService", UserService.class);

        System.out.println("Spring  IOC容器被创建了...............");

    }
}

1.1.4结果

1.2BeanFactory

  • spring中工厂的类结构图

BeanFactory:是在 getBean 的时候才会创建对象。

1.2.1service

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public UserServiceImpl(UserDao userDao, String msg) {
        this.userDao = userDao;
        this.msg = msg;
    }

    @Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

1.2.2applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl" autowire="byType">
    </bean>



</beans>

1.2.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) {
 /**
         * 测试BeanFactory和ApplicationContext的区别
         */
        //new ClassPathXmlApplicationContext("applicationContext.xml");
        XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
       UserService userService = xbf.getBean("userService", UserService.class);

        System.out.println("Spring  IOC容器被创建了...............");

    }
}

1.2.4结果

1.3BeanFactroy和ApplicationContext区别

BeanFactroy:顶级接口,getBean时才创建对象

ApplicationContext:子接口,加载配置文件时就创建对象

2.bean的作用范围

2.1概述

  • 在Spring中,bean作用域用于确定bean实例应该从哪种类型的Spring容器中返回给调用者。

2.2五种作用域

目前Spring Bean的作用域或者说范围主要有五种:

作用域 说明
singleton 默认值,Bean以单例方式存在spring IoC容器
prototype 每次从容器中调用Bean时都返回一个新的实例,相当于执行newInstance()
request WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中
session WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中
application WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 ServletContext 域中

可以通过 <bean> 标签的scope 属性控制bean的作用范围,其配置方式如下所示:

<bean id="..." class="..." scope="singleton"/>

  • 需要根据场景决定对象的单例、多例模式

    单例:Service、DAO、SqlSessionFactory(或者是所有的工厂)

    多例:Connection、SqlSession

2.3测试单例singleton

2.3.1service

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public UserServiceImpl(UserDao userDao, String msg) {
        this.userDao = userDao;
        this.msg = msg;
    }

    @Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

2.3.2applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl" scope="singleton" autowire="byType">
    </bean>



</beans>

2.3.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) {
  /**
         * bean的五种作用范围
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        for (int i = 0; i < 5; i++) {
            UserService userService = context.getBean("userService", UserService.class);
            System.out.println(userService);
        }
    }
}

2.3.4结果

2.4测试原型模式(多例)prototype

2.4.1service

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public UserServiceImpl(UserDao userDao, String msg) {
        this.userDao = userDao;
        this.msg = msg;
    }

    @Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

2.4.2 applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl" scope="prototype" autowire="byType">
    </bean>



</beans>

2.4.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) {
  /**
         * bean的五种作用范围
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        for (int i = 0; i < 5; i++) {
            UserService userService = context.getBean("userService", UserService.class);
            System.out.println(userService);
        }
    }
}

2.4.4结果

3.bean的生命周期

3.1单例bean

3.1.1service

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    /**
     *
     */

    public void setUserDao(UserDao userDao) {
        System.out.println("使用set注入....");
        this.userDao = userDao;
    }
    public void init(){
        System.out.println("初始化bean....");
    }
    public void destroy(){
        System.out.println("销毁bean....");
    }
@Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

3.1.2applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
<!--    <bean id="userService" class="com.by.service.UserServiceImpl" scope="prototype" autowire="byType">-->
    <bean id="userService" class="com.by.service.UserServiceImpl" scope="singleton"
          init-method="init" destroy-method="destroy" autowire="byType">
   </bean>



</beans>

3.1.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) { 
 /**
         * bean的生命周期
         * 单例模式的周期:[容器启动时]--》set方法注入-->构造方法(实例化对象)--->init(初始化)---》[关闭容器]---》destory(销毁)
         * 多例模式的周期:使用对象时---》set方法注入---》构造方法(实例化对象)---->init(初始化)----》jvm销毁对象,释放内存----》destroy(销毁)
         */
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 关闭容器
        context.close();
        // context.getBean("userService", UserService.class);


    }
}

3.1.4结果

3.2原型模式、多例bean

3.2.1service

java 复制代码
package com.by.service;

import com.by.dao.UserDao;
import com.by.dao.UserDaoImpl;

public class UserServiceImpl implements UserService{
    private UserDao userDao;
   private String msg;


    public UserServiceImpl() {
        System.out.println("测UserServiceImpl对象创建了...");
    }
    /**
     *
     */

    public void setUserDao(UserDao userDao) {
        System.out.println("使用set注入....");
        this.userDao = userDao;
    }
    public void init(){
        System.out.println("初始化bean....");
    }
    public void destroy(){
        System.out.println("销毁bean....");
    }
@Override
    public void adduser() {
        System.out.println(userDao+"============"+msg);
           userDao.adduser();
    }
}

3.2.2applicationContext.xml

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
<!--    <bean id="userService" class="com.by.service.UserServiceImpl" scope="prototype" autowire="byType">-->
    <bean id="userService" class="com.by.service.UserServiceImpl" scope="prototype"
          init-method="init" destroy-method="destroy" autowire="byType">
   </bean>



</beans>

3.2.3测试

java 复制代码
package com.by.web;

import com.by.dao.UserDao;
import com.by.service.UserService;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ContextResource;

public class Client {
    public static void main(String[] args) { 
 /**
         * bean的生命周期
         * 单例模式的周期:[容器启动时]--》set方法注入-->构造方法(实例化对象)--->init(初始化)---》[关闭容器]---》destory(销毁)
         * 多例模式的周期:使用对象时---》set方法注入---》构造方法(实例化对象)---->init(初始化)----》jvm销毁对象,释放内存----》destroy(销毁)
         */
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 关闭容器
       // context.close();
        context.getBean("userService", UserService.class);


    }
}

3.2.4结果

3.3总结

spring bean的生命周期

1、单例

[容器启动]---->构造方法(实例化)----->set方法(注入)----->init方法(初始化)---->[容器关闭]---->destroy方法(销毁)

2、多例

[使用对象]---->构造方法(实例化)----->set方法(注入)----->init方法(初始化)---->[jvm垃圾回收]--->destroy方法(销毁)

相关推荐
P.H. Infinity31 分钟前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天35 分钟前
java的threadlocal为何内存泄漏
java
caridle1 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
萧鼎1 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
学地理的小胖砸1 小时前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农1 小时前
Python 继承、多态、封装、抽象
开发语言·python
^velpro^1 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋31 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
秋の花1 小时前
【JAVA基础】Java集合基础
java·开发语言·windows
小松学前端1 小时前
第六章 7.0 LinkList
java·开发语言·网络