Spring5源码 - Aware

本文解析了Spring框架中的Aware接口如何帮助组件获取ApplicationContext和其他Bean实例,展示了如何在Controller中通过ApplicationContextAware接口获取ApplicationContext,并实现多个Aware接口以获取不同资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从Bean中获取到的容器实例并对其进行操作。

public interface Aware {

}

该接口只能当做是一个顶级接口使用,主要依赖于其下的子接口:

BeanFactoryAware 就是用于获取BeanFactory相关的信息。

ResourceLoaderAware 就是用于获取ResourceLoader相关信息。

以此类推。

故在以上子接口中,均包含一个setter方法。什么意思呢?

例如,当前有个Controller类需要获取ApplicationContext这个Bean,那么这个Controller类可继承ApplicationContextAware接口,通过实现setter方法来获取到ApplicationContext实例。

@Controller
public class DemoController implements ApplicationContextAware {
    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public void hello() {
        System.out.println(context);
    }
}

此外,当然可以同时实现多个接口获得多个想要得到的Bean,例如:

@Controller
public class DemoController implements ApplicationContextAware, BeanNameAware {
    private ApplicationContext context;

    private String myName;

    @Autowired
    private DemoService demoService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setBeanName(String name) {
        this.myName = name;
    }

    public void hello() {
        demoService.hello("来自Controller的问候");
        System.out.println("我是:" + myName);
        // 获取容器中所有的Bean
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            System.out.println(myName + "获取到:" + name);
        }
    }
}

执行结果:

来自Controller的问候
我是:demoController
demoController获取到:org.springframework.context.annotation.internalConfigurationAnnotationProcessor
demoController获取到:org.springframework.context.annotation.internalAutowiredAnnotationProcessor
demoController获取到:org.springframework.context.annotation.internalCommonAnnotationProcessor
demoController获取到:org.springframework.context.event.internalEventListenerProcessor
demoController获取到:org.springframework.context.event.internalEventListenerFactory
demoController获取到:application
demoController获取到:customizedBeanDefinitionPostProcessor
demoController获取到:customizedBeanPostProcessor
demoController获取到:demoController
demoController获取到:demoServiceImpl
demoController获取到:user5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值