java 中 @Resource 的java实现多态的机制机制

400-650-7353
深入理解 Java 中的 try-with-resource
子曾经曰过:所有的炒冷饭都是温故而知新。
众所周知,所有被打开的系统资源,比如流、文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。
在Java的江湖中,存在着一种名为finally的功夫,它可以保证当你习武走火入魔之时,还可以做一些自救的操作。在远古时代,处理资源关闭的代码通常写在finally块中。然而,如果你同时打开了多个资源,那么将会出现噩梦般的场景:
public class Demo {
public static void main(String[] args) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
bin = new BufferedInputStream(new FileInputStream(new File(&test.txt&)));
bout = new BufferedOutputStream(new FileOutputStream(new File(&out.txt&)));
while ((b = bin.read()) != -1) {
bout.write(b);
catch (IOException e) {
e.printStackTrace();
if (bin != null) {
bin.close();
catch (IOException e) {
e.printStackTrace();
if (bout != null) {
bout.close();
catch (IOException e) {
e.printStackTrace();
Oh My God!!!关闭资源的代码竟然比业务代码还要多!!!这是因为,我们不仅需要关闭BufferedInputStream,还需要保证如果关闭BufferedInputStream时出现了异常,&BufferedOutputStream也要能被正确地关闭。所以我们不得不借助finally中嵌套finally大法。可以想到,打开的资源越多,finally中嵌套的将会越深!!!
更为可恶的是,Python面对这个问题,竟然微微一笑很倾城地说:&这个我们一点都不用考虑的嘞~&:
但是兄弟莫慌!我们可以利用Java 1.7中新增的try-with-resource语法糖来打开资源,而无需码农们自己书写资源来关闭代码。妈妈再也不用担心我把手写断掉了!我们用try-with-resource来改写刚才的例子:
public class TryWithResource {
public static void main(String[] args) {
try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File(&test.txt&)));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File(&out.txt&)))) {
while ((b = bin.read()) != -1) {
bout.write(b);
catch (IOException e) {
e.printStackTrace();
是不是很简单?是不是很刺激?再也不用被Python程序员鄙视了!好了,下面将会详细讲解其实现原理以及内部机制。
为了能够配合try-with-resource,资源必须实现AutoClosable接口。该接口的实现类需要重写close方法:
public class Connection implements AutoCloseable {
public void sendData() {
System.out.println(&正在发送数据&);
public void close() throws Exception {
System.out.println(&正在关闭连接&);
public class TryWithResource {
public static void main(String[] args) {
try (Connection conn = new Connection()) {
conn.sendData();
catch (Exception e) {
e.printStackTrace();
运行后输出结果:
正在发送数据
正在关闭连接
通过结果我们可以看到,close方法被自动调用了。
那么这个是怎么做到的呢?我相信聪明的你们一定已经猜到了,其实,这一切都是编译器大神搞的鬼。我们反编译刚才例子的class文件:
public class TryWithResource {
public TryWithResource() {
public static void main(String[] args) {
Connection e = new Connection();
Throwable var2 = null;
e.sendData();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if(e != null) {
if(var2 != null) {
e.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
e.close();
} catch (Exception var14) {
var14.printStackTrace();
看到没,在第15~27行,编译器自动帮我们生成了finally块,并且在里面调用了资源的close方法,所以例子中的close方法会在运行的时候被执行。
我相信,细心的你们肯定又发现了,刚才反编译的代码(第21行)比远古时代写的代码多了一个addSuppressed。为了了解这段代码的用意,我们稍微修改一下刚才的例子:我们将刚才的代码改回远古时代手动关闭异常的方式,并且在sendData和close方法中抛出异常:
public class Connection implements AutoCloseable {
public void sendData() throws Exception {
throw new Exception(&send data&);
public void close() throws Exception {
throw new MyException(&close&);
修改main方法:
public class TryWithResource {
public static void main(String[] args) {
catch (Exception e) {
e.printStackTrace();
private static void test() throws Exception {
Connection conn = null;
conn = new Connection();
conn.sendData();
if (conn != null) {
conn.close();
运行之后我们发现:
.exception.MyException:
.exception.Connection.close(.java:10)
.exception.TryWithResource.test(.java:82)
.exception.TryWithResource.main(.java:7)
好的,问题来了,由于我们一次只能抛出一个异常,所以在最上层看到的是最后一个抛出的异常&&也就是close方法抛出的MyException,而sendData抛出的Exception被忽略了。这就是所谓的异常屏蔽。由于异常信息的丢失,异常屏蔽可能会导致某些bug变得极其难以发现,程序员们不得不加班加点地找bug,如此毒瘤,怎能不除!幸好,为了解决这个问题,从Java 1.7开始,大佬们为Throwable类新增了addSuppressed方法,支持将一个异常附加到另一个异常身上,从而避免异常屏蔽。那么被屏蔽的异常信息会通过怎样的格式输出呢?我们再运行一遍刚才用try-with-resource包裹的main方法:
.lang.Exception:
.exception.Connection.sendData(.java:5)
.exception.TryWithResource.main(.java:14)
: .exception.MyException:
.exception.Connection.close(.java:10)
.exception.TryWithResource.main(.java:15)
可以看到,异常信息中多了一个Suppressed的提示,告诉我们这个异常其实由两个异常组成,MyException是被Suppressed的异常。可喜可贺!
一个小问题
在使用try-with-resource的过程中,一定需要了解资源的close方法内部的实现逻辑。否则还是可能会导致资源泄露。
举个例子,在Java BIO中采用了大量的装饰器模式。当调用装饰器的close方法时,本质上是调用了装饰器内部包裹的流的close方法。比如:
public class TryWithResource {
public static void main(String[] args) {
try (FileInputStream fin = new FileInputStream(new File(&input.txt&));
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(&out.txt&)))) {
byte[] buffer = new byte[4096];
while ((read = fin.read(buffer)) != -1) {
out.write(buffer, 0, read);
catch (IOException e) {
e.printStackTrace();
在上述代码中,我们从FileInputStream中读取字节,并且写入到GZIPOutputStream中。GZIPOutputStream实际上是FileOutputStream的装饰器。由于try-with-resource的特性,实际编译之后的代码会在后面带上finally代码块,并且在里面调用fin.close()方法和out.close()方法。我们再来看GZIPOutputStream类的close方法:
public void close() throws IOException {
if (!closed) {
if (usesDefaultDeflater)
def.end();
out.close();
closed = true;
我们可以看到,out变量实际上代表的是被装饰的FileOutputStream类。在调用out变量的close方法之前,GZIPOutputStream还做了finish操作,该操作还会继续往FileOutputStream中写压缩信息,此时如果出现异常,则会out.close()方法被略过,然而这个才是最底层的资源关闭方法。正确的做法是应该在try-with-resource中单独声明最底层的资源,保证对应的close方法一定能够被调用。在刚才的例子中,我们需要单独声明每个FileInputStream以及FileOutputStream:
public class TryWithResource {
public static void main(String[] args) {
try (FileInputStream fin = new FileInputStream(new File(&input.txt&));
FileOutputStream fout = new FileOutputStream(new File(&out.txt&));
GZIPOutputStream out = new GZIPOutputStream(fout)) {
byte[] buffer = new byte[4096];
while ((read = fin.read(buffer)) != -1) {
out.write(buffer, 0, read);
catch (IOException e) {
e.printStackTrace();
由于编译器会自动生成fout.close()的代码,这样肯定能够保证真正的流被关闭。
怎么样,是不是很简单呢,如果学会了话
官方微信更多精彩,扫码关注 或微信搜索:ujiuye
官方微博更多精彩,扫码关注 或微博搜索:优就业
注:本站稿件未经许可不得转载,转载请保留出处及源文件地址。
(责任编辑:zhangjs)
关键词阅读
[免责声明]本文来源于网络转载,仅供学习交流使用,不构成商业目的。版权归原作者所有,如涉及作品内容、版权和其它问题请在30日内与本网联系,我们将在第一时进行处理
(点击一键加群)他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)@Autowired和@Resource使用,区别以及工作原理 - 为程序员服务
@Autowired和@Resource使用,区别以及工作原理
首先这两个annotation都是用来自动注入依赖的。
举个例子:
当我们在一个bean a中声明这样一段
private UserService userService
@Autowired
private UserService userService
spring 容器在初始化bean a的时候就会把userService自动注入到bean a中去
虽然两者都可以完成bean的自动注入,但是如果我们不注意他们的区别,就很容易出错。
例如我们在spring容器中定义了两个bean
&bean id=”userService1″/&
&bean id=”userService2″/&
这个时候使用
@Autowired
private UserService userService1
spring容器将会报错
换一种方式
private UserService userService1
则可以正常启动
从上面这个例子很容易一些端倪,事实上
1. @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
2. @Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:
@Autowired() @Qualifier(“baseDao”)
private BaseDao baseD
3.@Resource(这个注解属于J2EE的),默认安装名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
尽管这两个annation很方便,至少我们不用为每个bean写set方法了,但是它并不是自动工作的,我们还需要一些额外的配置。
有两种配置方式,它们都可以达到一样的效果:
添加两个bean定义
简化配置,添加配置
&context:annotation-config/&
&context:annotationconfig/& 将隐式地向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个 BeanPostProcessor。
在配置文件中使用 context 命名空间之前,必须在 &beans& 元素中声明 context 命名空间
很明显方法2只是将配置简化了而已,最终的目的还是添加了两个bean定义
它们分别对应@Autowired和@Resource
那么这两个bean是干什么的?它们又是如何完成自动注入的?webx3框架并没有配置这两个bean为什么却支持@Autowired和@Resource?
要回答这两个问题,我们先得从spring容器的初始化说起,以webx3定制的spring容器为例,顺便说明webx3为什么能支持@Autowired和@Resource
webx3定制spring容器是通过扩展AbstractApplicationContext来完成的,其中有个重要的方法来完成容器的初始化:
public void refresh() throws BeansException, IllegalStateException {
synchronized ( this.startupShutdownMonitor ) {
// Prepare this context for refreshing.
prepareRefresh ();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory (beanFactory);
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory (beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors (beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors (beanFactory);
// Initialize message source for this context.
initMessageSource ();
// Initialize event multicaster for this context.
initApplicationEventMulticaster ();
// Initialize other special beans in specific context subclasses.
onRefresh ();
// Check for listener beans and register them.
registerListeners ();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization (beanFactory);
// Last step: publish corresponding event.
finishRefresh ();
catch ( BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
beanFactory .destroySingletons();
// Reset ‘active’ flag.
cancelRefresh (ex);
// Propagate exception to caller.
这是把初始化的生命周期拆分成了多个phase,spring允许你通过覆盖这些phase对应的方法来完成加入相应的逻辑,这里我们就不扩展了。
如上图所示,webx3引入了定制的spring容器XmlWebApplicationContext,在这个类中它覆盖了customizeBeanFactory方法
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
super.customizeBeanFactory (beanFactory);
registerAnnotationConfigProcessors (beanFactory, null);
spring容器在初始化的最终会调用这段方法
我们看看 registerAnnotationConfigProcessors ( beanFactory , null )这段代码究竟做了什么
public static Set&BeanDefinitionHolder & registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry , Object source) {
Set &BeanDefinitionHolder& beanDefinitions = new LinkedHashSet& BeanDefinitionHolder&(4 );
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if ( jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME )) {
RootBeanDefinition def = new RootBeanDefinition();
ClassLoader cl = AnnotationConfigUtils. class.getClassLoader ();
def .setBeanClass(cl.loadClass (PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME));
catch ( ClassNotFoundException ex) {
throw new IllegalStateException(
“Cannot load optional framework class: “ + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
def .setSource(source);
def .setRole(BeanDefinition.ROLE_INFRASTRUCTURE );
beanDefinitions .add( registerBeanPostProcessor(registry , def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if ( jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME )) {
RootBeanDefinition def = new RootBeanDefinition( CommonAnnotationBeanPostProcessor.class );
def .setSource(source);
def .setRole(BeanDefinition.ROLE_INFRASTRUCTURE );
beanDefinitions .add( registerBeanPostProcessor(registry , def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME )) {
RootBeanDefinition def = new RootBeanDefinition( AutowiredAnnotationBeanPostProcessor.class );
def .setSource(source);
def .setRole(BeanDefinition.ROLE_INFRASTRUCTURE );
beanDefinitions .add( registerBeanPostProcessor(registry , def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME )) {
RootBeanDefinition def = new RootBeanDefinition( RequiredAnnotationBeanPostProcessor.class );
def .setSource(source);
def .setRole(BeanDefinition.ROLE_INFRASTRUCTURE );
beanDefinitions .add( registerBeanPostProcessor(registry , def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
return beanDefinitions;
事实上这段代码和和上面提到的方法2做的事情完全一样,把4个BeanPostProcessor注册到BeanDefinition中去。
分析到这儿想必大家已经为什么webx3框架并没有配置这两个bean却支持@Autowired和@Resource了。
但是我们依然不明白这些beanProcessor是干嘛用的,以及它们是如何完成自动注入的,别着急,我们接着分析:
首先注意到上面的refresh方法有这么一段:
// Register bean processors that intercept bean creation.
registerBeanPostProcessors (beanFactory);
对应的实现片段:
* Instantiate and invoke all registered BeanPostProcessor beans,
* respecting explicit order if given.
* &p&Must be called before any instantiation of application beans.
protected void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory) {
String [] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class , true , false );
spring会从beanFactory中拿出所有实现了BeanPostProcessor 接口并重新注册到一个数据结构中方便后续查询
接下来的使用则出现在bean的初始化过程中
for ( Iterator it = getBeanPostProcessors ().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = ( BeanPostProcessor) it.next();
if ( beanProcessor instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor;
if (!ibp. postProcessAfterInstantiation(bw .getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false ;
只要BeanPostProcessor同时实现了InstantiationAwareBeanPostProcessor 接口,那么它的postProcessAfterInstantiation 方法就会被调用,我们以CommonAnnotationBeanPostProcessor为例说明:
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable
它满足了我们定义的两个条件,即实现了InstantiationAwareBeanPostProcessor 和BeanPostProcessor 接口
public boolean postProcessAfterInstantiation (Object bean, String beanName) throws BeansException {
InjectionMetadata metadata = findResourceMetadata( bean.getClass ());
metadata .injectFields(bean, beanName );
catch ( Throwable ex) {
throw new BeanCreationException(beanName , “Injection of resource fields failed”, ex);
return true ;
方法的具体实现细节这里不展开了,我们总结一下这个方法完成的事情:
收集类里的annotation信息,找到声明了@Resource annoation的属性(还有其它的annatation,并且还会扫描方法上的annotation,这里不展开了)
从BeanFactory里找到这些annotation声明过的bean
通过反射的方法把这些被依赖到的bean类赋给对应的属性
于是乎,自动依赖注入完成了。
There is no certainty, only opportunity
原文地址:, 感谢原作者分享。
您可能感兴趣的代码  JDK1.5加入了对注解机制的支持,实际上我学习Java的时候就已经使用JDK1.6了,而且除了@Override和@SuppressWarnings(后者还是IDE给生成的&&)之外没接触过其他的。
  进入公司前的面试,技术人员就问了我关于注解的问题,我就说可以生成chm手册&&现在想起来真囧,注释和注解被我搞得完全一样了。
  使用注解主要是在需要使用Spring框架的时候,特别是使用SpringMVC。因为这时我们会发现它的强大之处:预处理。
  注解实际上相当于一种标记,它允许你在运行时(源码、文档、类文件我们就不讨论了)动态地对拥有该标记的成员进行操作。
  实现注解需要三个条件(我们讨论的是类似于Spring自动装配的高级应用):注解声明、使用注解的元素、操作使用注解元素的代码。
  首先是注解声明,注解也是一种类型,我们要定义的话也需要编写代码,如下:
3 import java.lang.annotation.ElementT
4 import java.lang.annotation.R
5 import java.lang.annotation.RetentionP
6 import java.lang.annotation.T
* 自定义注解,用来配置方法
* @author Johness
14 @Retention(RetentionPolicy.RUNTIME) // 表示注解在运行时依然存在
15 @Target(ElementType.METHOD) // 表示注解可以被使用于方法上
16 public @interface SayHiAnnotation {
String paramValue() default "johness"; // 表示我的注解需要一个参数 名为"paramValue" 默认值为"johness"
  然后是使用我们注解的元素:
3 import annotation.SayHiA
* 要使用SayHiAnnotation的元素所在类
* 由于我们定义了只有方法才能使用我们的注解,我们就使用多个方法来进行测试
* @author Johness
12 public class SayHiEmlement {
// 普通的方法
public void SayHiDefault(String name){
System.out.println("Hi, " + name);
// 使用注解并传入参数的方法
@SayHiAnnotation(paramValue="Jack")
public void SayHiAnnotation(String name){
System.out.println("Hi, " + name);
// 使用注解并使用默认参数的方法
@SayHiAnnotation
public void SayHiAnnotationDefault(String name){
System.out.println("Hi, " + name);
  最后,是我们的操作方法(值得一提的是虽然有一定的规范,但您大可不必去浪费精力,您只需要保证您的操作代码在您希望的时候执行即可):
1 package M
3 import java.lang.reflect.InvocationTargetE
4 import java.lang.reflect.M
6 import element.SayHiE
7 import annotation.SayHiA
9 public class AnnotionOperator {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
SayHiEmlement element = new SayHiEmlement(); // 初始化一个实例,用于方法调用
Method[] methods = SayHiEmlement.class.getDeclaredMethods(); // 获得所有方法
for (Method method : methods) {
SayHiAnnotation annotationTmp = null;
if((annotationTmp = method.getAnnotation(SayHiAnnotation.class))!=null) // 检测是否使用了我们的注解
method.invoke(element,annotationTmp.paramValue()); // 如果使用了我们的注解,我们就把注解里的"paramValue"参数值作为方法参数来调用方法
method.invoke(element, "Rose"); // 如果没有使用我们的注解,我们就需要使用普通的方式来调用方法了
  结果为:Hi, Jack      Hi, johness      Hi, Rose
  可以看到,注解是进行预处理的很好方式(这里的预处理和编译原理有区别)!
  接下来我们看看Spring是如何使用注解机制完成自动装配的:
    首先是为了让Spring为我们自动装配要进行的操作,无外乎两种:继承org.springframework.web.context.support.SpringBeanAutowiringSupport类或者添加@Component/@Controller等注解并(只是使用注解方式需要)在Spring配置文件里声明context:component-scan元素。
    我说说继承方式是如何实现自动装配的,我们打开Spring源代码查看SpringBeanAutowiringSupport类。我们会发现以下语句:
1 public SpringBeanAutowiringSupport() {
processInjectionBasedOnCurrentContext(this);
    众所周知,Java实例构造时会调用默认父类无参构造方法,Spring正是利用了这一点,让"操作元素的代码"得以执行!(我看到第一眼就震惊了!真是奇思妙想啊。果然,高手都要善于用Java来用Java)
    后面的我就不就不多说了,不过还是要纠正一些人的观点:说使用注解的自动装配来完成注入也需要setter。这明显是错误的嘛!我们看Spring注解装配(继承方式)的方法调用顺序:&org.springframework.web.context.support.SpringBeanAutowiringSupport#SpringBeanAutowiringSupport=&
    &&& org.springframework.web.context.support.SpringBeanAutowiringSupport#processInjectionBasedOnCurrentContext=&
     &org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#processInjection=&
&&&&&&&&&&&&&& org.springframework.beans.factory.annotation.InjectionMetadata#Injection(继承,方法重写)。最后看看Injection方法的方法体:
* Either this or {@link #getResourceToInject} needs to be overridden.
protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable {
if (this.isField) {
Field field = (Field) this.
ReflectionUtils.makeAccessible(field);
field.set(target, getResourceToInject(target, requestingBeanName));
if (checkPropertySkipping(pvs)) {
Method method = (Method) this.
ReflectionUtils.makeAccessible(method);
method.invoke(target, getResourceToInject(target, requestingBeanName));
catch (InvocationTargetException ex) {
throw ex.getTargetException();
      虽然不完全,但可以基本判定此种自动装配是使用了java放射机制。
&欢迎您移步我们的交流群,无聊的时候大家一起打发时间:
&或者通过QQ与我联系:
&(最后编辑时间 09:52:27)
阅读(...) 评论()

我要回帖

更多关于 java实现多态的机制 的文章

 

随机推荐