Spring中Aware系列接口

(一)IOC容器管理bean,bean在IOC容器中。那么bean知不知道自己在IOC容器中的代号(id)呢?bean知不知道自己在哪个IOC容器中?能否通过bean获取它的IOC容器对象呢?简单来说就是:bean是否对Spring有知觉

答:单纯的bean(未实现Aware系列接口)是没有知觉的;实现了Aware系列接口的bean可以访问Spring容器。
这些Aware系列接口增强了Spring bean的功能,但是也会造成对Spring框架的绑定,增大了与Spring框架的耦合度。
(Aware是“意识到的,察觉到的”的意思,实现了Aware系列接口表明:可以意识到、可以察觉到)
(二)首先,看一下Aware系列接口
这里写图片描述
(三)Aware系列接口的共性
(1)都以“Aware”结尾
(2)都是Aware接口的子接口,即都继承了Aware接口
(3)接口内均定义了一个set方法
(四)Aware系列接口的set方法
(1)父接口Aware中没有定义任何方法,只是一个标识接口

public interface Aware {
}

(2)观察一下这些set方法
ApplicationContextAware接口:

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

BeanNameAware接口:

public interface BeanNameAware extends Aware {
    void setBeanName(String name);
}

BeanClassLoaderAware接口:

public interface BeanClassLoaderAware extends Aware {
    void setBeanClassLoader(ClassLoader classLoader);
}

ApplicationContextAware接口:“Aware”前面的“ApplicationContext”就是我们需要Aware(知道,获取)的内容。
set方法的形参ApplicationContext applicationContext就用于接收我们需要获取的那个对象。
会把我们需要Aware的内容,注给set方法的形参,我们需要定义一个成员属性来保存形参。
(五)代码示例:

//实现BeanNameAware接口,才能获取bean在IOC容器中的id
//还可以实现ApplicationContextAware接口,用于获取bean所在的IOC容器
public class HelloWorld implements BeanNameAware{

    private String beanName;
    @Override
    public void setBeanName(String name) {//id会被传给形参name
        this.beanName=name;//把id保存在成员属性beanName中
    }

    public String getBeanName(){
        return beanName;
    }
}

在 bean配置文件中,注册一个id为“hello”的bean:

<bean class="com.HelloWorld" id="hello"></bean>
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloWorld h=(HelloWorld)context.getBean("hello");
        System.out.println(h.getBeanName());
    }

输出结果:
hello

Aware系列接口,用于辅助Spring bean访问Spring容器;
Aware系列接口,都定义了一个set 方法,体现了set方法注入的思想;
这些接口的作用与@Autowired、@Resource等注解有点类似;
在Struts2中,也有Aware系列接口:RequestAware;SessionAware;ApplicationAware;ParameterAware等。这些接口的设计思想和Spring里面的Aware系列接口的设计思想是一致的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值