激活Aware

目录

1、概述

2、BeanFactoryAware 示例

创建普通类

创建BeanFactoryAware

spring配置

spring引导类

运行结果


1、概述

Spring 提供了一些 Aware接口,比如BeanFactoryAware、ApplicationContextAware、ResourceLoaderAware等,实现Aware接口的bean在被初始化之后,可以取得一些相对应的资源。例如BeanFactoryAware 在 bean 初始化后,Spring容器将会注入 BeanFactory 的实例。

2、BeanFactoryAware 示例

创建普通类

package thinking.in.spring.boot.samples.spring5.aware;

public class Hello {
    public void say() {
        System.out.println("hello aware");
    }
}

创建BeanFactoryAware

package thinking.in.spring.boot.samples.spring5.aware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class HelloAware implements BeanFactoryAware {
    private BeanFactory beanFactory;
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void testHelloAware() {
        Hello hello = (Hello) this.beanFactory.getBean("hello");
        hello.say();
    }
}

spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:customLabel="http://www.rh.com/schema/customLabel"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.rh.com/schema/customLabel
        http://www.rh.com/schema/customLabel.xsd">

    <bean id="hello" class="thinking.in.spring.boot.samples.spring5.aware.Hello" />
    <bean id="helloAware" class="thinking.in.spring.boot.samples.spring5.aware.HelloAware" />

</beans>

spring引导类

package thinking.in.spring.boot.samples.spring5.bootstrap;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import thinking.in.spring.boot.samples.spring5.aware.HelloAware;
import thinking.in.spring.boot.samples.spring5.circle.CircleA;
import thinking.in.spring.boot.samples.spring5.circle.CircleB;
import thinking.in.spring.boot.samples.spring5.circle.CircleC;

public class AwareBootstrap {

    public static void main(String[] args) {
        DefaultListableBeanFactory defaultListableBeanFactory = new XmlBeanFactory(new ClassPathResource("application-aware.xml"));
        HelloAware helloAware = (HelloAware)defaultListableBeanFactory.getBean("helloAware");
        helloAware.testHelloAware();
    }
}

运行结果

信息: Loading XML bean definitions from class path resource [application-aware.xml]
hello aware

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值