Spring: register advice programmatically at runtime

会有一股神秘感。 提交于 2019-12-06 07:28:04

问题


Is it possible to register AOP advices programmatically, after the application has booted and the context has been initialized?

When I tried, the advices didn't work, supposedly because they need to wrap the bean BEFORE it gets available in the context.

Something like this (it doesn't work):

@Bean
private AspectJExpressionPointcutAdvisor createPointcutAdvisor(AWSXRayRecorder awsxRayRecorder, String name, String pointcut) {

    AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
    advisor.setExpression("execution ...()");
    advisor.setAdvice(new CustomAdvice("custom bean"));

    return advisor;
  }

Clarification: I need to read a list of advice from a config file, and register the pointcuts accordingly. I need the label for bookeeping purposes. The file contents are unknown at compile time.

label: execution(* com.my.ns.OtherClass(..))
label2: execution(* com.my.ns.Class(..)) 

回答1:


Maybe programmatic creation of @AspectJ Proxies according to the Spring AOP manual does what you want. Quoting from there because answers with external links only are frowned upon on SO:

// create a factory that can generate a proxy for the given target object
AspectJProxyFactory factory = new AspectJProxyFactory(targetObject);

// add an aspect, the class must be an @AspectJ aspect
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager.class);

// you can also add existing aspect instances, the type of the
// object supplied must be an @AspectJ aspect
factory.addAspect(usageTracker);

// now get the proxy object...
MyInterfaceType proxy = factory.getProxy();

Update:

So actually I played around a bit, not being a Spring user but rather an AspectJ expert. But anyway I found a way to dynamically register an advisor with a custom pointcut. The thing is, though, you need to know which beans you want to apply it to, and be careful to differentiate between beans which are already proxied and ones which are not.

Question: When in your application lifecycle and to which beans do you want to add the advisors? Have your other beans already been instantiated and wired (injected) into others? I am asking because it is quite easy to register advisors to beans you have direct references to, wrapping them into proxies or adding the advisors to existing proxies. But there is no obvious way to wrap a bean which has already been injected into other beans and not proxied yet. So how easy or difficult the solution is depends on your requirements.

P.S.: I am still wondering why your pointcuts are in a properties file instead of just in a Spring XML config file, which would be the standard way. That XML file is also loaded during application start-up. Where does the requirement to use another file come from? Both are basically editable (text) resource files.


Update 2:

Okay, I have created a GitHub repo for you. Just build with Maven and run the class with the main(..) method. It looks like this:

package de.scrum_master.performancemonitor;

import org.aopalliance.aop.Advice;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class PerformanceApp {
  public static DefaultPointcutAdvisor createAdvisor(String pointcutExpression, Advice advice) {
    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression(pointcutExpression);
    return new DefaultPointcutAdvisor(pointcut, advice);
  }

  public static Object adviseIfNecessary(Object bean, DefaultPointcutAdvisor advisor) {
    final String pointcutExpression = advisor.getPointcut().toString().replaceAll(".*\\(\\) ", "");
    if (!advisor.getPointcut().getClassFilter().matches(bean.getClass())) {
      System.out.println("Pointcut " + pointcutExpression + " does not match class " + bean.getClass());
      return bean;
    }
    System.out.println("Pointcut " + pointcutExpression + " matches class " + bean.getClass() + ", advising");
    Advised advisedBean = createProxy(bean);
    advisedBean.addAdvisor(advisor);
    return advisedBean;
  }

  public static Advised createProxy(Object bean) {
    if (bean instanceof Advised) {
      System.out.println("Bean " + bean + " is already an advised proxy, doing nothing");
      return (Advised) bean;
    }
    System.out.println("Creating proxy for bean " + bean);
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setTarget(bean);
    return (Advised) proxyFactory.getProxy();
  }

  public static void main(String[] args) {
    DefaultPointcutAdvisor advisor = createAdvisor(
      // Just load this from your YAML file as needed
      "execution(public int de.scrum_master.performancemonitor.PersonService.getAge(..))",
      new MyPerformanceMonitorInterceptor(true)
    );

    ApplicationContext context = new AnnotationConfigApplicationContext(AopConfiguration.class);
    Person person = (Person) adviseIfNecessary(context.getBean("person"), advisor);
    PersonService personService = (PersonService) adviseIfNecessary(context.getBean("personService"), advisor);

    System.out.println();
    System.out.println("Name: " + personService.getFullName(person));
    System.out.println("Age: " + personService.getAge(person));
    System.out.println();

    // BTW, you can also unadvise a bean like this.
    // Write your own utility method for it if you need it.
    ((Advised) personService).removeAdvisor(advisor);
    System.out.println("Name: " + personService.getFullName(person));
    System.out.println("Age: " + personService.getAge(person));
  }
}

The console log looks like this:

Pointcut execution(public int de.scrum_master.performancemonitor.PersonService.getAge(..)) does not match class class de.scrum_master.performancemonitor.Person
Pointcut execution(public int de.scrum_master.performancemonitor.PersonService.getAge(..)) matches class class de.scrum_master.performancemonitor.PersonService$$EnhancerBySpringCGLIB$$965d1d14, advising
Bean de.scrum_master.performancemonitor.PersonService@2fd1433e is already an advised proxy, doing nothing

web - 2018-03-10 09:14:29,229 [main] TRACE d.s.performancemonitor.PersonService - StopWatch 'de.scrum_master.performancemonitor.PersonService.getFullName': running time (millis) = 2
Name: Albert Einstein
web - 2018-03-10 09:14:29,235 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution started at: Sat Mar 10 09:14:29 ICT 2018
web - 2018-03-10 09:14:29,332 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution lasted: 100 ms
web - 2018-03-10 09:14:29,332 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution ended at: Sat Mar 10 09:14:29 ICT 2018
web - 2018-03-10 09:14:29,332 [main] WARN  d.s.performancemonitor.PersonService - Method execution longer than 10 ms!
Age: 146

web - 2018-03-10 09:14:29,334 [main] TRACE d.s.performancemonitor.PersonService - StopWatch 'de.scrum_master.performancemonitor.PersonService.getFullName': running time (millis) = 0
Name: Albert Einstein
Age: 146

You can nicely see how log output from the advisor gets printed. After detaching the advisor again, the log output goes away and only the log output from the advisor defined in class AopConfiguration remains. I.e. you can mix Spring configuration with your own dynamically attached advisors.

BTW, if you comment out the @Bean annotation in AopConfiguration like this

//@Bean
public Advisor performanceMonitorAdvisor() {

then class PersonService will not be proxied already by the time you attach your dynamic advisor and the console output changes to:

Pointcut execution(public int de.scrum_master.performancemonitor.PersonService.getAge(..)) does not match class class de.scrum_master.performancemonitor.Person
Pointcut execution(public int de.scrum_master.performancemonitor.PersonService.getAge(..)) matches class class de.scrum_master.performancemonitor.PersonService, advising
Creating proxy for bean de.scrum_master.performancemonitor.PersonService@6a03bcb1

Name: Albert Einstein
web - 2018-03-10 09:43:04,633 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution started at: Sat Mar 10 09:43:04 ICT 2018
web - 2018-03-10 09:43:04,764 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution lasted: 136 ms
web - 2018-03-10 09:43:04,769 [main] INFO  d.s.performancemonitor.PersonService - Method de.scrum_master.performancemonitor.PersonService.getAge execution ended at: Sat Mar 10 09:43:04 ICT 2018
web - 2018-03-10 09:43:04,769 [main] WARN  d.s.performancemonitor.PersonService - Method execution longer than 10 ms!
Age: 146

Name: Albert Einstein
Age: 146

Please note that not only the log lines produces by the Spring-configured advisor go away as expected but that also the line

Bean de.scrum_master.performancemonitor.PersonService@2fd1433e is already an advised proxy, doing nothing

changes to

Creating proxy for bean de.scrum_master.performancemonitor.PersonService@6a03bcb1


来源:https://stackoverflow.com/questions/49072611/spring-register-advice-programmatically-at-runtime

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