2017-01-18 1 views
2

스프링에 의해 특정 Aspect로 프록시 처리 된 빈의 목록을 얻는 방법이 있습니까? 스프링에있는 aspect-proxied beans의 목록

우리는 작동이 중지 일부 콩 측면을 가지고, 우리는 무슨 일이 있었는지 알아 내기 위해 노력하고있다, 그래서 나는이

@Component 
public class AspectScanner implements ApplicationListener<ContextRefreshedEvent> { 

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

    @Override 
    public void onApplicationEvent(ContextRefreshedEvent event) { 
     final ApplicationContext applicationContext = event.getApplicationContext(); 
     applicationContext.[GET PROXIED BEANS CALL]; 
    } 
} 

어떤 제안을로드 한 후 ApplicationContext를 스캔 할 수있는 클래스를 생성?

답변

1

권장 콩을 식별하려면 org.springframework.aop.framework.Advised을 구현하는지 확인하고 가로 세로 이름을 가져 오려면 org.springframework.aop.aspectj.AspectJPrecedenceInformation#getAspectName을 사용해야합니다. 다음은 개념 증명 코드입니다.

@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(); 
    } 

}