Spring Bean&生命周期图&扩展接口介绍&spring的简化配置

2023-09-13 16:54:47

目录

1. 生命周期简图

2. 扩展接口介绍

2.1 Aware接口

2.2 BeanPostProcessor接口

2.3 InitializingBean

2.4 DisposableBean

2.5 BeanFactoryPostProcessor接口

3. spring的简化配置

3.1 项目搭建

3.2 Bean的配置和值注入

3.3 AOP的示例


1. 生命周期简图

2. 扩展接口介绍

2.1 Aware接口

在spring中Aware接口表示的是感知接口,表示spring框架在Bean实例化过程中以回调的方式将特定在资源注入到Bean中去(如:ApplicationContext, BeanName,BeanFactory等等)。Aware接口本事没有声明任何方法,是一个标记接口,其下有多个子接口,如:BeanNameAware,ApplicationContextAware,BeanFactoryAware等。
每个特定的子接口都会固定一个特定的方法,并注入特定的资源,如BeanFactoryAware接口,定义了setBeanFactory(BeanFactory beanFactory),在spring框架实例化Bean过程中,将回调该接口,并注入BeanFactory对象。再例如:ApplicationContextAware接口,定义了setApplicationContext(ApplicationContext applicationContext) 方法,在spring完成Bean实例化,将回调该接口,并注入ApplicationContext对象(该对象即spring的上下文)。

Aware接口示例(ApplicationContextAware 是 Aware 接口的子接口):

public class ApplicationContextAwareTest implements ApplicationContextAware {

    private static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
        System.out.println("---- ApplicationContextAware 示例 -----------");
    }

    public static  <T> T getBean(String beanName) {
        return (T) ctx.getBean(beanName);
    }

}

 配置文件:

<bean id="applicationContextAwareTest" class="org.lisen.springstudy.aware.ApplicationContextAwareTest">
</bean>

2.2 BeanPostProcessor接口

Bean在初始化之前会调用该接口的postProcessBeforeInitialization方法,在初始化完成之后会调用
postProcessAfterInitialization方法。

除了我们自己定义的BeanPostProcessor实现外,spring容器也会自动加入几个,如ApplicationContextAwareProcessor、ApplicationListenerDetector,这些都是BeanPostProcessor的实现类。

BeanPostProcessor接口的定义:

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}

方法的第一个参数为bean实例,第二个参数为beanName,且返回值类型为Object,所以这给功能扩展留下了很大的空间,比如:我们可以返回bean实例的代理对象。

开发示例:

public class BeanPostProcessorTest implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(beanName + " postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(beanName + " postProcessAfterInitialization");
        return bean;
    }

}

配置文件:

<bean id="beanPostProcessorTest" 
class="org.lisen.springstudy.beanpostprocessor.BeanPostProcessorTest"></bean>

2.3 InitializingBean

该接口是Bean初始化过程中提供的扩展接口,接口中只定义了一个afterPropertiesSet方法。如果一个bean实现了InitializingBean接口,则当BeanFactory设置完成所有的Bean属性后,会回调afterPropertiesSet方法,可以在该接口中执行自定义的初始化,或者检查是否设置了所有强制属性等。

也可以通过在配置init-method方法执行自定义的Bean初始化过程。

示例:

public class InitializingBeanTest implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean.afterPropertiesSet() ......");
    }

}

配置文件:

<bean id="initializingBeanTest" class="org.lisen.springstudy.initializingbean.InitializingBeanTest">
</bean>

2.4 DisposableBean

实现了DisposableBean接口的Bean,在该Bean消亡时Spring会调用这个接口中定义的destroy方法。

public class TestService implements DisposableBean {

    public void hello() {
        System.out.println("hello work ... ");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("TestService destroy ..... ");
    }
}

在Spring的应用上下文关闭时,spring会回调destroy方法, 如果Bean需要自定义清理工作,则可以实现该接口。

除了实现DisposableBean接口外,还可以配置destroy-method方法来实现自定义的清理工作。

2.5 BeanFactoryPostProcessor接口

该接口并没有在上面的流程图上体现出来,因为该接口是在Bean实例化之前调用的(但BeanFactoryPostProcessor接口也是spring容器提供的扩展接口,所以在此处一同列出),如果有实现了BeanFactoryPostProcessor接口,则容器初始化后,并在Bean实例化之前Spring会回调该接口的postProcessorBeanFactory方法,可以在这个方法中获取Bean的定义信息,并执行一些自定义的操作,如属性检查等。

3. spring的简化配置

3.1 项目搭建

启用注解,对spring的配置进行简化。

  1. 创建一个maven web工程
  2. 将web改为web3.1,参考第一次课件
  3. 修改pom.xml文件,引入必要的包
<properties>
		<spring.version>5.3.18</spring.version>
		<junit.version>4.12</junit.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<!-- junit 测试 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		

	</dependencies>

在resources根目录下添加spring的配置文件 spring.xml

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context.xsd">
        
	<context:component-scan base-package="com.zking"/>
	
	<!-- 配置properties文件,与Spring @Value 配合使用   方式一    -->
	<!-- <bean >
		<property name="locations">
			<list>
				<value>classpath:/test.properties</value>
			</list>
		</property>
	</bean>
	
	<bean >
		<property name="properties" ref="configProp"></property>
	</bean> -->
	
	
	<!-- 
	配置properties文件,与Spring @Value 配合使用   方式二 。
	也可以不使用xml的方式配置,使用程序方式进行配置,可以参考ConfigurationBean  方式三
	-->
	<bean id="propPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:/test.properties</value>
			</list>
		</property>
	</bean>
	
</beans>

 程序方式注册如下:

@Configuration
public class ConfigurationBean {
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer setPropertiesFile() {
		PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer();
		ClassPathResource contextPath = new ClassPathResource("/test.properties");
		config.setLocation(contextPath);
		return config;
	}

}
  1. 在resources根目录下新建一个test.properties文件,和spring.xml的配置文件中的配置是相对应的

3.2 Bean的配置和值注入

  1. 创建并注册一个Bean
@Component("stu")
public class Student {
	
	//@Value("#{configProp['stu.name']}")
	@Value("${stu.name}")
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + "]";
	}

}
  1. 通过容器获取Bean

	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		Student stu = (Student)ctx.getBean("stu");
		//stu.setName("zs");
		System.out.println(stu);

3.3 AOP的示例

  1. 创建一个切面,记录程序运行时间
@Component
@Aspect
@EnableAspectJAutoProxy
public class ProcessAop {
	//execution(* com.cybx..*.*(..))
	/*@Pointcut("@annotation(com.zking.mavendemo.config.MyAnnotation)")
	public void logPointcut() {
	}*/
	
	@Around("execution(* com.zking.mavendemo.service..*.hello*(..))")
	public Object around(ProceedingJoinPoint  joinPoint) throws Throwable {
		
		Class<? extends Signature> signatureClass = joinPoint.getSignature().getClass();
		System.out.println("AOP signatureClass = " + signatureClass);
		
		Object target = joinPoint.getTarget();
		Class<? extends Object> targetClass = target.getClass();
		System.out.println("AOP targetClass = " + targetClass);
		
		Object returnValue = joinPoint.proceed(joinPoint.getArgs());
		
		System.out.println("AOP After ... ");
		
		return returnValue;
	}
	
}
  1. 创建一个service接口和实现类演示AOP且面
    接口:
public interface ITestService {	
	void helloAop(String msg);
}

实现类:

@Service("testService")
public class TestService implements ITestService {

	@Override
	public void helloAop(String msg) {
		System.out.println("target obj method: " + msg);
	}

}

测试:

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		ITestService bean = (ITestService)ctx.getBean("testService");
		bean.helloAop("fdfdfdfdfdfdfdf");

更多推荐

软件测试之功能测试详解

一、功能测试概述1)功能测试就是对产品的各功能进行验证,根据功能测试用例,逐项测试,检查产品是否达到用户要求的功能。2)功能测试,根据产品特性、操作描述和用户方案,测试一个产品的特性和可操作行为以确定它们满足设计需求。本地化软件的功能测试,用于验证应用程序或网站对目标用户能正确工作。使用适当的平台、浏览器和测试脚本,以

数据研发“新人”如何快速落地?

作者:肖迪(墨诩)一、前言这个季度主推安全月构筑&夯实稳定性底盘,就组织了组里的同学对核心业务链路进行了稳定性的摸排。在摸排过程中,不断有个声音在问你摸排出来的问题就是全部问题么?你加的监控加全了么?你的技改方案考虑全了么?(这个声音主要来自左耳,因为我leader坐在我的左边,哈哈哈哈)所以我们一直在思考和对焦,如何

SpringMVC之JSON数据返回及异常处理机制

目录一.JSON数据的返回二.异常处理机制2.1异常处理方式一2.2异常处理方式二2.3异常处理方式三一.JSON数据的返回JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,常用于Web应用程序和服务之间的数据传输。通过使用JSON,数据可以以一种结构化的方式进行组织和存储,并可以

图像处理领域之►边缘检测大合集◄【应该是全网仅有的了吧】

图像处理领域之►边缘检测‧大合集◄概述{\color{Brown}概述}概述数据集{\color{Purple}数据集}数据集实践{\color{Red}实践}实践深度学习方法{\color{Blue}深度学习方法}深度学习方法机器学习方法{\color{Blue}机器学习方法}机器学习方法基于传统方法{\color{

掌握进度管理基本指南,保证项目不延期

项目管理中的进度管理是规划、制定、控制和监控项目时间表的过程,确保任务和活动按时完成。假设你是一名项目经理,带着团队组织一场备受瞩目的音乐节。精确的时间安排是关键。你需要确保演出者准时到达并按计划表演,所有供应商都准备就绪,安保人员到位。你可能会遇到一些问题,如音响设备车延误了、某位演出者无法到场而你需要在最后一刻换人

北斗+渔业:且看北斗卫星如何提升渔业监管水平

近日,为确保渔业船舶海上航行安全和管理,海南省农业农村厅近日发布通告:全省小型海洋渔船须于今年9月30日前完成北斗船载终端安装,大中型海洋渔船须于今年11月30日前同时完成北斗船载终端和“插卡式AIS”终端安装。近年来,北斗卫星在渔业监管方面的应用越来越普遍,发挥着越来越重要的作用。本文将详细介绍北斗卫星在渔业监管中的

基于当量因子法、InVEST、SolVES模型等多技术融合在生态系统服务功能社会价值评估中的应用及论文写作、拓展分析

生态系统服务是人类从自然界中获得的直接或间接惠益,可分为供给服务、文化服务、调节服务和支持服务4类,对提升人类福祉具有重大意义,且被视为连接社会与生态系统的桥梁。自从启动千年生态系统评估项目(MillenniumEcosystemAssessment,MA)以来,生态系统服务成为学术界的研究热点,其中在生态系统服务功能

netty之ObjectPool(对象池)

对象池和我们的连接池一样就是对象放入一个池中循环使用。特别是在netty创建ByteBuf的时候buf循环使用大大减小了频繁创建对象,垃圾收集的压力。特别是在使用直接内存的时候。netty的对象池对象RecyclerObjectPoolextendsObjectPool。RecyclerObjectPool只是外层抽象

exev函数族

一.exev函数族1.1功能exec()函数族的主要功能是在当前进程中运行一个新的程序。使用这些函数可以实现以下功能:程序替换(ProgramReplacement):调用exec()函数后,当前进程的代码和数据会被新程序的代码和数据替换。这可以用于动态加载和替换程序,使得一个进程可以切换到运行不同的程序,实现灵活的程

Java版工程行业管理系统源码-专业的工程管理软件- 工程项目各模块及其功能点清单

鸿鹄工程项目管理系统SpringCloud+SpringBoot+Mybatis+Vue+ElementUI+前后端分离构建工程项目管理系统1.项目背景一、随着公司的快速发展,企业人员和经营规模不断壮大。为了提高工程管理效率、减轻劳动强度、提高信息处理速度和准确性,公司对内部工程管理的提升提出了更高的要求。二、企业通过

5G面试题目和答案,计算机面试

以下是一些5G面试的题目和答案,供您参考:5G是什么?与4G相比有哪些主要区别和优势?5G是指第五代移动通信技术,它是在4G的基础上进一步发展而来的。相比4G,5G具有更高的数据传输速度、更低的延迟、更高的网络容量和更好的连接稳定性。它的优势包括:支持更多的设备、更快的传输速度、更低的延迟、更高的网络容量、更好的连接稳

热文推荐