Spring源码解析之基础应用(二)
方法注入
在spring容器中,大部分bean的作用域(scope)是单例(singleton)的,少部分bean的作用域是原型(prototype),如果一个bean的作用域是原型,我们A bean的作用域是原型,B bean中以@Autowired的方式注入A,那么B在A中依旧是单例。我们可以让B类实现ApplicationContextAware接口,这个接口会注入一个ApplicationContext对象,如果我们有需要A bean,则从ApplicationContextAware对象中获取。
package org.example.service; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; @Component
@Scope("prototype")
public class CommandService {
} import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; @Component
public class CommandManager implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Autowired
private CommandService commandService; public CommandService getCommandService() {
return commandService;
} //方法注入
public CommandService createCommandService() {
return applicationContext.getBean(CommandService.class);
} @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
} package org.example.config; import org.springframework.context.annotation.ComponentScan; @ComponentScan("org.example.service")
public class MyConfig {
}
为了验证笔者之前的说法,笔者特意在CommandManager类中注入一个原型的commandService的bean,也提供了方法注入,从applicationContext中获取CommandService对象。现在,我们编写测试用例,CommandManager有两种获取CommandService的方式,一种是getCommandService(),一种是createCommandService(),我们的目标是希望每次获取CommandService对象都是新创建的对象。
@Test
public void test05() {
ApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
CommandManager commandManager = ac.getBean(CommandManager.class);
//获取@Autowired注入的CommandService
System.out.println(commandManager.getCommandService());
System.out.println(commandManager.getCommandService());
//获取方法注入的CommandService
System.out.println(commandManager.createCommandService());
System.out.println(commandManager.createCommandService());
}
运行结果:
org.example.service.CommandService@351d0846
org.example.service.CommandService@351d0846
org.example.service.CommandService@77e4c80f
org.example.service.CommandService@35fc6dc4
除了像上面那样从环境上下文获取CommandService对象之外,我们还可以借助@Lookup注解:
package org.example.service; import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component; @Component
public abstract class CommandManager1 {
@Lookup
public abstract CommandService createCommandService();
} import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component; @Component
public class CommandManager2 {
@Lookup
public CommandService createCommandService() {
return null;
}
}
测试用例:
@Test
public void test06() {
ApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
CommandManager1 commandManager1 = ac.getBean(CommandManager1.class);
System.out.println(commandManager1.createCommandService());
System.out.println(commandManager1.createCommandService());
CommandManager2 commandManager2 = ac.getBean(CommandManager2.class);
System.out.println(commandManager2.createCommandService());
System.out.println(commandManager2.createCommandService());
}
运行结果:
org.example.service.CommandService@6193932a
org.example.service.CommandService@647fd8ce
org.example.service.CommandService@159f197
org.example.service.CommandService@78aab498
不管是CommandManager1还是CommandManager2,spring在对这两个类生成代理对象,当调用被@Lookup注解标记的方法时,产生新的原型对象返回。
生命周期
从spring2.5开始,我们有三种选项来控制bean生命周期行为:
- InitializingBean和DisposableBean回调接口。
- 自定义init()和destroy()方法。
- @PostConstruct和@PreDestroy注解。
我们可以使用上面三种选项来控制bean在不同生命周期时机进行函数回调,比如当一些dao在spring创建好之后,在回调方法里执行热点数据加载。下面的A类,我们按照第一和第三个选项,实现InitializingBean、DisposableBean接口,并标注@PostConstruct、@PreDestroy方法,分别是aaa()、bbb()。然后,我们在配置类MyConfig2通过@Bean注解获取一个类型为A的bean,并且按照第二个选项,在@Bean标注了init()和destroy()方法,分别是ccc()、ddd()。
package org.example.beans; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; public class A implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("A destroy...");
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("A afterPropertiesSet...");
} @PostConstruct
public void aaa() {
System.out.println("A aaa...");
} @PreDestroy
public void bbb() {
System.out.println("A bbb...");
} public void ccc() {
System.out.println("A ccc...");
} public void ddd() {
System.out.println("A ddd...");
}
} package org.example.config; import org.example.beans.A;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan("org.example.service")
public class MyConfig2 {
@Bean(initMethod = "ccc", destroyMethod = "ddd")
public A getA() {
return new A();
}
}
测试用例:
@Test
public void test07() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig2.class);
ac.close();
}
运行结果:
A aaa...
A afterPropertiesSet...
A ccc...
A bbb...
A destroy...
A ddd...
从上面的执行结果,我们可以得出:如果存在不同的初始化方法,bean的回调顺序是:
- 先执行@PostConstruct注解所标注的方法。
- 再执行InitializingBean接口所实现的afterPropertiesSet()方法
- 最后执行自定义的init()方法。
销毁方法也是一样的顺序:
- 先执行@PreDestroy注解所标注的方法。
- 在执行DisposableBean接口所实现的destroy()方法。
- 最后执行自定义的destroy()方法。
服务启动关闭回调
之前我们学习了bean的生命周期回调,我们可以在bean的不同生命周期里执行不同的方法,如果我们想针对整个服务进行生命周期回调呢?比如要求在spring容器初始化好所有的bean之后、或者在关闭spring容器时进行方法回调。spring提供了LifeCycle接口来帮助我们实现针对服务的生命周期回调。LifeCycle提供了三个接口:
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
当isRunning()返回为false时,start()会在初始化完所有的bean之后,进行回调。比如我们可以在初始化好所有的bean之后,监听一个消息队列,并处理队列里的消息。当isRunning()返回为true时,stop()会在容器关闭时回调stop()方法。
来看下面的例子,TestLiftCycle的isRunning()默认返回false,所以在bean初始化后,允许spring容器回调start(),在start()方法中,将isRun置为true,允许在spring容器关闭时,回调stop()方法。
package org.example.service; import org.springframework.context.Lifecycle;
import org.springframework.stereotype.Component; @Component
public class TestLiftCycle implements Lifecycle {
private boolean isRun = false; @Override
public void start() {
isRun = true;
System.out.println("TestLiftCycle start...");
} @Override
public void stop() {
System.out.println("TestLiftCycle stop...");
} @Override
public boolean isRunning() {
return isRun;
}
}
要回调TestLiftCycle的start()和stop(),在测试用例里需要显式调用容器的start()和stop()方法。如果项目是部署在类似Tomcat、JBoss的微博服务器上,我们可以省去容器显式调用stop()方法,因为Tweb服务器在结束进程的时候,会回调spring容器的stop(),进而回调到我们编写的stop(),但是start()必须显式调用,不管是否部署在web服务器上。
测试用例:
@Test
public void test08() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
ac.start();
ac.stop();
}
运行结果:
TestLiftCycle start...
TestLiftCycle stop...
为了方便程序员偷懒,spring还提供了SmartLifecycle接口,这个接口不需要我们显式调用容器的start()方法,也可以在初始化所有的bean之后回调start()。下面,我们来看下SmartLifecycle接口:
public interface SmartLifecycle extends Lifecycle, Phased {
boolean isAutoStartup();
void stop(Runnable callback);
}
SmartLifecycle扩展了Lifecycle和Phased两个接口,Phased要求实现int getPhase()接口,返回的数值越低越优先执行。boolean isAutoStartup()代表是否自动执行SmartLifecycle的start()方法,如果为true会自动调用start(),为false的话,需要显式调用容器的start()才会回调SmartLifecycle的start()。SmartLifecycle扩展了原先Lifecycle的stop()方法,当我们执行完stop(Runnable callback)中的业务,需要执行callback.run(),这将启用异步关闭,否则要等待30s才会关闭容器。当然,这30s是可以修改的:
<bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
<!-- timeout value in milliseconds -->
<property name="timeoutPerShutdownPhase" value="10000"/>
</bean>
下面,我们来测试TestSmartLifecycle,这里的isRunning()依旧和Lifecycle一样,只是关闭容器时不会再回调TestSmartLifecycle的stop(),转而回调stop(Runnable callback)。
package org.example.service; import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component; @Component
public class TestSmartLifecycle implements SmartLifecycle {
private boolean isRun = false; @Override
public void start() {
isRun = true;
System.out.println("TestSmartLifecycle start...");
} @Override
public boolean isAutoStartup() {
return true;
} @Override
public void stop(Runnable callback) {
System.out.println("TestSmartLifecycle stop callback...");
//执行callback.run()可以让容器立即关闭,否则容器会等待30s再关闭
callback.run();
} @Override
public int getPhase() {
return 0;
} @Override
public void stop() {
} @Override
public boolean isRunning() {
return isRun;
} }
测试用例:
@Test
public void test09() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
ac.stop();
}
运行结果:
TestSmartLifecycle start...
TestSmartLifecycle stop callback...
Spring源码解析之基础应用(二)的更多相关文章
- Spring源码解析之ConfigurationClassPostProcessor(二)
上一个章节,笔者向大家介绍了spring是如何来过滤配置类的,下面我们来看看在过滤出配置类后,spring是如何来解析配置类的.首先过滤出来的配置类会存放在configCandidates列表, 在代 ...
- Spring源码解析之BeanFactoryPostProcessor(二)
上一章,我们介绍了在AnnotationConfigApplicationContext初始化的时候,会创建AnnotatedBeanDefinitionReader和ClassPathBeanDef ...
- Spring源码解析之基础应用(三)
组合Java配置 在XML中,我们可以使用<import/>标签,在一个XML文件中引入另一个XML文件,在Java类中,我们同样可以在一个配置类中用@Import引入另一个配置类,被引入 ...
- Spring源码解析之BeanFactoryPostProcessor(三)
在上一章中笔者介绍了refresh()的<1>处是如何获取beanFactory对象,下面我们要来学习refresh()方法的<2>处是如何调用invokeBeanFactor ...
- Spring源码解析 - AbstractBeanFactory 实现接口与父类分析
我们先来看类图吧: 除了BeanFactory这一支的接口,AbstractBeanFactory主要实现了AliasRegistry和SingletonBeanRegistry接口. 这边主要提供了 ...
- spring 源码解析
1. [文件] spring源码.txt ~ 15B 下载(167) ? 1 springн┤┬вио╬Ш: 2. [文件] spring源码分析之AOP.txt ~ 15KB 下载( ...
- Spring源码解析——循环依赖的解决方案
一.前言 承接<Spring源码解析--创建bean>.<Spring源码解析--创建bean的实例>,我们今天接着聊聊,循环依赖的解决方案,即创建bean的ObjectFac ...
- Spring源码解析-ioc容器的设计
Spring源码解析-ioc容器的设计 1 IoC容器系列的设计:BeanFactory和ApplicatioContext 在Spring容器中,主要分为两个主要的容器系列,一个是实现BeanFac ...
- Spring源码解析系列汇总
相信我,你会收藏这篇文章的 本篇文章是这段时间撸出来的Spring源码解析系列文章的汇总,总共包含以下专题.喜欢的同学可以收藏起来以备不时之需 SpringIOC源码解析(上) 本篇文章搭建了IOC源 ...
随机推荐
- LiteOS间歇计算技术:IOT终端真正感受“电量自由”
摘要:LiteOS间歇计算为什么能使物联网终端实现长续航? 物联网设备.场景复杂多样,小到智能穿戴的耳机,大到大型基建设备,更有我们陌生而又熟悉场景,例如深海探测.森林监控.野生动物跟踪等等能量采集场 ...
- SpringMVC-08-SpringMVC层编写
SpringMVC层编写 web.xml DispatcherServlet <!--DispatcherServlet--> <servlet> <servlet-na ...
- oracle之dblink
当用户要跨本地Oracle数据库,访问另外一个数据库表中的数据时,本地数据库中必须创建了远程数据库的dblink,通过dblink本地数据库可以像访问本地数据库一样访问远程数据库表中的数据.下面讲介绍 ...
- pytest文档2-pytest+Allure+jenkins+邮箱发送
前言: 上一章节讲解了tomcat+jenkins的环境搭建,这一章节主要讲一下Allure报告在jenkins上的配置 步骤: 1.新建一个item 2.输入项目的名称,选择自由风格,点击保存 3. ...
- 关于java基础语法的学习笔记
*java语言特点 1,简单易用 2,跨平台 拥有JVM虚拟机(运行程序) 3,面向对象 4,支持多线程*java核心机制 1,java虚拟机 JVM 2,垃圾回收机制*JDK和JRE JDK JRE ...
- VC 编译 MATLAB 的 mex 文件
VC 编译 MATLAB 的 mex 文件mex 文件是 MATLAB 调用其他程序设计语言程序或算法的接口.在 Windows 环境中,mex 文件是扩展文件名为 DLL 的动态链接库,可以在 m ...
- Qt 展示pdf内容(新窗口或嵌入,pdfjs,linux)
前言:初学Qt,在网上查找了诸多资料,有什么poppler.mupdf啊巴拉巴拉的,结果一个比一个费劲,最后还是采用pdfjs较为方便高效,为方便相关问题搜索,写了一下内容. 需求描述:Qt应用中不支 ...
- 【JAVA】校招面过的信息量最大的一面
这是我校招中面过的信息量最大的一面,本来是一个小时,最后面完一个半小时,面试官最后反馈还不错. 自我介绍 设计模式有了解吗?如何理解"宁用组合,不用继承",什么时候用组合,什么时候 ...
- dedecmsv5.7sp1远程文件包含漏洞审计
dedecms5.7 sp1版本存在远程文件包含漏洞,在此记录审计复现漏洞过程. 漏洞在/install/index.php(index.php.bak)文件中,漏洞起因是$$符号使用不当,导致变量覆 ...
- JavaScript,你好!(二)
操作BOM对象 浏览器介绍 JavaScript和浏览器的关系? JavaScrpit诞生就是为了能够让它在浏览器中运行! BOM:浏览器对象模型 IE 6~11 Chrome Safari Fire ...