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.** <p>Note that merely implementing {@link Aware} provides no default* functionality. Rather, processing must be done explicitly, for example* in a {@link org.springframework.fig.BeanPostProcessor BeanPostProcessor}.* Refer to {@link t.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框架自身的一些对象来执行一些操作,比如:
org.springframework.beans.factory.Aware
标记接口,并提供一个将由Bean实现的Set方法,Spring通过基于Setter的依赖注入方式使相应的对象可以被Bean使用。以BeanNameAware为例:
BeanNameAware:使对象能够知道容器中定义的bean名称。
public class MyBeanName implements BeanNameAware {@Overridepublic void setBeanName(String beanName){System.out.println(beanName);}
}
在Spring配置类中注册这种类型的bean:
@Configuration
public class Config{@Bean(name="WangBeanName")public MyBeanName getMyBeanName(){return new MyBeanName();
}}
启动应用程序上下文并从中获取bean:
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
MyBeanName myBeanName = Bean(MyBeanName.class);
从控制台可以看到,setBeanName方法打印出来了"WangBeanName"。
若从@Bean注解中删除name =“…”代码,则在这种情况下,将getMyBeanName()方法名称分配给bean,所以输出将是“getMyBeanName”。
对于这个接口我觉得说这么多就好,其实重点在于它的设计模式,后面写到设计模式的时候我再把它拿回来说。
本文发布于:2024-02-05 07:55:58,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170727818364728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |