Listing Aspect-proxied beans in Spring

血红的双手。 提交于 2019-12-06 10:08:52

To identify advised bean you should check if it implements org.springframework.aop.framework.Advised and use org.springframework.aop.aspectj.AspectJPrecedenceInformation#getAspectName to get aspect name. Proof of concept code is presented below.

@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class AspectScanner implements ApplicationListener<ContextRefreshedEvent> {

    public static final Logger LOGGER = LoggerFactory.getLogger(AspectScanner.class);

    public void onApplicationEvent(ContextRefreshedEvent event) {
        final ApplicationContext applicationContext = event.getApplicationContext();
        Map<String, Object> beansOfType = applicationContext.getBeansOfType(Object.class);
        for (Map.Entry<String, Object> entry : beansOfType.entrySet()) {
            boolean advisedWith = isAdvisedWith(applicationContext, entry.getValue(), BeanAspect.class);
            LOGGER.info(entry.getKey() + (advisedWith ? " is advised" : " isn't advised"));
        }
    }

    private static boolean isAdvisedWith(ApplicationContext context, Object bean, Class<?> aspectClass) {
        boolean advisedWith = false;
        HashSet<String> names = new HashSet<>(Arrays.asList(context.getBeanNamesForType(aspectClass)));
        if (bean instanceof Advised) {
            Advisor[] advisors = ((Advised) bean).getAdvisors();
            for (Advisor advisor : advisors) {
                if (advisor instanceof AspectJPrecedenceInformation) {
                    if (names.contains(((AspectJPrecedenceInformation) advisor).getAspectName())) {
                        advisedWith = true;
                    }
                }
            }
        }
        return advisedWith;
    }


    @Aspect
    @Component
    public static class BeanAspect {

        @Before("execution(* test.AspectScanner.Bean*.*(..))")
        public void beforeAny(JoinPoint jp) {

        }

    }

    @Component
    public static class Bean1 {

        public void m() {

        }

    }

    public interface Bean2Intf {

        void m();

    }

    @Component
    public static class Bean2 implements Bean2Intf {

        public void m() {

        }

    }

    @Component
    public static class NotAdvised {

        public void n() {

        }

    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AspectScanner.class);
        context.start();
        context.registerShutdownHook();
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!