ApplicationContextAware

Spring提供的一个扩展接口,在Spring项目加载完所有的Bean实例后会调用该接口的实现。

自定义类实现ApplicationContextAware

package com.unfbx.eventTest.config;

import com.unfbx.eventTest.annotation.TestLog;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogAware implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //通过applicationContext实例可以获取所有的Bean对象
    }
}

应用场景

做一个获取Bean实例的工具类


public class LogAware implements ApplicationContextAware {
    //内部持有一个容器
    private static ApplicationContext applicationContext;

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

    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name)
    }
    
    //by Type get bean
}

获取自定义注解Bean实例

这个还是很有用处的,通过自定义注解可以实现很多操作,比如结合Aop实现接口日志的记录,接口耗时统计等等。

@Component
public class LogAware implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取有TestLog注解的Bean对象
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(TestLog.class);
        beansWithAnnotation.forEach((k, v) -> {
            System.out.println(k);
            System.out.println(v);
        });
    }
}
文章目录