河南金城建设工程有限公司网站,比较有创意的互动h5,鹤壁网站推广,建设工程造价管理基础知识Aware接口前言基本内容例子结尾前言
Spring的依赖注入最大亮点是所有的Bean对Spring容器对存在都是没有意识到#xff0c;Spring容器中的Bean的耦合度是很低的#xff0c;我们可以将Spring容器很容易换成其他的容器。 但是实际开发的时候#xff0c;我们经常要用到Spring容…
Aware接口前言基本内容例子结尾前言
Spring的依赖注入最大亮点是所有的Bean对Spring容器对存在都是没有意识到Spring容器中的Bean的耦合度是很低的我们可以将Spring容器很容易换成其他的容器。 但是实际开发的时候我们经常要用到Spring容器本身的功能资源所以Spring容器中的Bean此时要能意识到Spring容器到存在才能调用Spring所提供的资源我们通过Spring提供的一系列接口Spring Aware来实现具体的功能。 Aware翻译过来“察觉的感知的”如果是XxxAware也就是对…感知的。
基本内容
Aware接口是一种框架辅助属性注入的一种思想其他框架中 瞧一眼源码
/*** Marker superinterface indicating that a bean is eligible to be* notified by the Spring container of a particular framework object* through a callback-style method. Actual method signature is* determined by individual subinterfaces, but should typically* consist of just one void-returning method that accepts a single* argument.** pNote that merely implementing {link Aware} provides no default* functionality. Rather, processing must be done explicitly, for example* in a {link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessor}.* Refer to {link org.springframework.context.support.ApplicationContextAwareProcessor}* and {link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory}* for examples of processing {code *Aware} interface callbacks.** author Chris Beams* since 3.1*/
public interface Aware {}我们可以看到Aware是一个具有标识作用的超级接口实现该接口的Bean都具有被Spring容器通知的能力。 而被通知的方式就是通过回调简单来说直接或者间接实现了这个接口的类都具有被Spring容器通知的能力。
Aware接口是回调监听器和观察者设计模式的混合它表示bean有资格通过回调方式被Spring容器通知。 有时我们的在Bean的初始化中使用Spring框架自身的一些对象来执行一些操作比如
获取ServletContext的一些参数。获取ApplicationContext中的BeanDefinition的名字。获取Bean在容器中的名字等等。 这些接口均继承自org.springframework.beans.factory.Aware标记接口并提供一个将由Bean实现的Set方法Spring通过基于Setter的依赖注入方式使相应的对象可以被Bean使用。 常见的Aware接口
例子
以BeanNameAware为例 BeanNameAware使对象能够知道容器中定义的bean名称。
public class MyBeanName implements BeanNameAware {Overridepublic void setBeanName(String beanName){System.out.println(beanName);}
}在Spring配置类中注册这种类型的bean:
Configuration
public class Config{Bean(nameWangBeanName)public MyBeanName getMyBeanName(){return new MyBeanName();
}}启动应用程序上下文并从中获取bean:
AnnotationConfigApplicationContext context new AnnotationConfigApplicationContext(Config.class);
MyBeanName myBeanName context.getBean(MyBeanName.class); 从控制台可以看到setBeanName方法打印出来了WangBeanName。 若从Bean注解中删除name “…”代码则在这种情况下将getMyBeanName()方法名称分配给bean所以输出将是“getMyBeanName”。
结尾
对于这个接口我觉得说这么多就好其实重点在于它的设计模式后面写到设计模式的时候我再把它拿回来说。