目录
1. 生命周期简图
生命周期:容器启动--->Bean实例化--->检查Aware接口属性填充设置依赖--->BeanPostProcessor前置处理--->是否实现InitializingBean接口--->执行初始化接口的方法--->是否配置自定义init-method--->执行自定义初始化方法-->BeanPostProcessor后置方法--->注册销毁的接口--->是否实现DisposabeBean接口--->执行销毁接口的方法--->是否配置自定义destory-method-->执行自定义的销毁方法
Spring帮助我们创建对象的具体步骤👇
上面这张图要从下往上看,橙色的框表示在spring中使用xml配置或者注解式开发,整个图也可以说是new ClassPathXmlApplicationContext("spring*.xml");这串代码具体做的事情:使用单例模式,只生成一个实例👇
- 当开发人员需要获取容器中的Bean时,就可以通过应用上下文API接口来获取(ApplicationContext)
- 当容器启动,就会读取配置文件,将配置文件中的内容转化成BeanDefinition(Bean定义),即实例化,将其转变成一个对象便于在中内存操作(相当于ORM映射的一种)
- BeanFactoryPostProcessor是一个扩展接口,检查是否有必须定义的Bean未定义、Bean中关键属性未设置,或者是否有重要的接口未实现等。中间的三条杠可以拓展的功能,实现了该接口的类,容器在会将你定义的规则一条条的检查判断是否通过(可以在此拓展,类似过滤器)。
- BeanFactory相当于IOC的一个抽象工厂模式,通过权限命名实例化Bean,并通过Set方式注入属性,为了避免循环依赖问题,不使用构造函数的方式注入。
- Aware结尾的接口是一个感知接口,根据接口的具体名称判断功能,比如ApplicationContext就是用来获取上下文的感知接口。感知接口中会将容器中的特定资源通过set方法给到特定的类,也可以在其中进行拓展。
- 在初始化Bean时,会先检查这个Bean有没有实现InitializingBean这个接口或者配置文件中有没有配置init-method,如果有就调用初始化方法
- (上图中黄色的横杠就相当于代理部分,AOP)BeanPostProcessor中有两个特定方法,会在Bean初始化前后进行拓展,详见下面接口的介绍👇
2. 扩展接口介绍
讲解上图中的接口的具体作用及其使用
BeanFactoryPostProcessor接口
该接口是在Bean实例化之前调用的(但BeanFactoryPostProcessor接口也是spring容器提供的扩展接口,所以在此处一同列出),如果有实现了BeanFactoryPostProcessor接口,则容器初始化后,并在Bean实例化之前Spring会回调该接口的postProcessorBeanFactory方法,可以在这个方法中获取Bean的定义信息,并执行一些自定义的操作,如属性检查等
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>
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>
InitializingBean接口
该接口是Bean初始化过程中提供的扩展接口,接口中只定义了一个afterPropertiesSet方法。如果一个bean实现了InitializingBean接口,则当BeanFactory设置完成所有的Bean属性后,会回调afterPropertiesSet方法,可以在该接口中执行自定义的初始化,或者检查是否设置了所有强制属性等。
也可以通过在配置init-method方法执行自定义的Bean初始化过程,init-method方法通常是无返回的
示例:
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>
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方法来实现自定义的清理工作
3. spring的简化配置
1、项目搭建
启用注解,对spring的配置进行简化,这也是现在常用的方式
1、创建一个maven web工程
2、将web改为web3.1,见上期:Maven的下载与使用_小阿飞_的博客-CSDN博客
3、修改pom.xml文件,引入必要的包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zking.spdemo</groupId> <artifactId>spdemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spdemo Maven Webapp</name> <url>http://maven.apache.org</url> <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> <build> <!-- 请改成自己项目的名字 --> <finalName>mavendemo</finalName> <plugins> <!--第一步就是配置maven-compiler-plugin插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
4、在resources根目录下添加spring的配置文件 spring.xml
<context:component-scan base-package="com.zking"/>即使用扫描器扫描指定包下的注解
<?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"/> <bean id="propPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/project.properties</value> </list> </property> </bean> </beans>
程序方式注册如下(java配置类)
配置类中的一个配置方法:相当于上面xml中配置id=propPlaceholder的bean,这两种配置方式作用相同,按照自己的习惯来选择
@Bean:配置一个bean
方法名PropertySourcesPlaceholderConfigurer 作为这个bean的id,并且在方法中进行初始化,和上面的配置文件中<property name="locations">
<list>
<value>classpath:/project.properties</value>
</list>
</property>的作用相同@Configuration public class ConfigurationBean { @Bean public static PropertySourcesPlaceholderConfigurer setPropertiesFile() { PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer(); ClassPathResource contextPath = new ClassPathResource("/project.properties"); config.setLocation(contextPath); return config; } }
5、在resources根目录下新建一个project.properties文件,和spring.xml的配置文件中的配置是相对应的👇
2、 Bean的配置和值注入
1、创建并注册一个Bean
//相当于xml中配置bean,但是这个bean没有配置id,默认为student @Component public class Student { //将配置文件project.properties中的属性值注入 @Value("${stu.name}") private String name; public String getName() { return name; } //但是在注入时使用的是注解,没有使用set注入 /* * public void setName(String name) { this.name = name; } */ @Override public String toString() { return "Student [name=" + name + "]"; } }
2、通过容器获取Bean
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml"); Student stu = (Student)ctx.getBean("student"); //stu.setName("zs"); System.out.println(stu);
3、AOP的示例
1、创建一个切面,记录程序运行时间
一个AOP拦截切面相当于AOP中的适配器(适配器=通知(Advice)+切入点(Pointcut))
@Component //中配置bean
@Aspect //一个切面
@EnableAspectJAutoProxy //用来开发切面的功能的代理
public class ProcessAop {
//方法参数ProceedingJoinPoint不可变
//环绕通知,拦截切面aop:
/**
* 1. 第一个* 对方法的返回值不作要求
* 2. com.zking.mavendemo.service 包名
* 3. .. 表示service包及其子包
* 4. 第二*表示所有的类
* 5. hello* 表示方法名以hello开头
* 6. (..) 表示对方法的参数不做要求
* @param joinPoint
* @return
* @throws Throwable
*/
//execution执行对象,*拦截方法的返回值,拦截的方法对象com.zking.spdemo.service..*.hello*(..)
@Around("execution(* com.zking.spdemo.service..*.hello*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
long t1=System.currentTimeMillis();
//调用目标方法
Object returnValue = joinPoint.proceed(joinPoint.getArgs());
long t2=System.currentTimeMillis();
System.out.println("所拦截的方法调用费时:"+(t2-t1));
return returnValue;
}
}
2、创建一个service接口和实现类演示AOP切面接口、实现类
public interface IStudentService {
void hello(String msg);
}
//@Component //spring托管的bean
//Service层的组件
@Service("studentService") //括号中可放id,也可不放
public class StudentService implements IStudentService{
@Override
public void hello(String msg) {
System.out.println(".....hello:"+msg);
}
}
3、测试
也可以使用注解进行测试👇
@RunWith(SpringJUnit4ClassRunner.class) //spring-test
//classpath:target下classpath下
@ContextConfiguration(locations = "classpath:spring.xml") //上下文配置文件的地址,在测试运行前获取上下文
public class BaseTest {
}
public class StudentTest extends BaseTest{
@Autowired //从容器中直接获取bean放入变量保存,不用get,set
private IStudentService studentService;
@Test
public void Test() {
studentService.hello("李四");
}
}
然后直接在类中右键选择jUnit Test进行测试即可