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

2024-01-09 20:06:03

1.Spring中的工厂类

1.1ApplicationContext

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

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

1.1.1service?

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

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 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测试

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

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 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测试

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()
requestWEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中
sessionWEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中
applicationWEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 ServletContext 域中

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

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

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

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

    多例:Connection、SqlSession

2.3测试单例singleton

?2.3.1service

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 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测试?

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

?

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 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测试?

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

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 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测试

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

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 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测试

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方法(销毁)

文章来源:https://blog.csdn.net/qq_62965575/article/details/135230880
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。