一、定义接口
package cn.edu.tju.study.service;
public interface MyService {
void myMethod();
}
二、定义实现类:
package cn.edu.tju.study.service;
public class MyServiceImpl implements MyService{
@Override
public void myMethod() {
System.out.println("hello world...");
}
}
三、定义配置类,配置业务bean、advisor bean、ProxyFactoryBean
package cn.edu.tju.study.service;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
//MethodBeforeAdvice
@Bean
public MethodBeforeAdvice beforeAdvice() {
MethodBeforeAdvice advice = new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("will call :"+ method);
System.out.println("args are: "+args);
}
};
return advice;
}
//MethodInterceptor
@Bean
public MethodInterceptor methodInterceptor() {
MethodInterceptor methodInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("before method invoke......");
Object re = invocation.proceed();
System.out.println("after method invoke......");
return re;
}
};
return methodInterceptor;
}
//MethodInterceptor2
@Bean
public MethodInterceptor methodInterceptor2() {
MethodInterceptor methodInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("before method invoke2......");
Object re = invocation.proceed();
System.out.println("after method invoke2......");
return re;
}
};
return methodInterceptor;
}
//ProxyFactoryBean
@Bean
public ProxyFactoryBean proxyFactoryBean() {
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTargetName("myService");
proxyFactoryBean.setInterceptorNames("beforeAdvice", "methodInterceptor", "methodInterceptor2");
return proxyFactoryBean;
}
}
四、定义主类,获取ProxyFactoryBean并使用文章来源:https://www.toymoban.com/news/detail-598257.html
package cn.edu.tju.study.service;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AopAnnotationTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(MyConfig.class);
context.refresh();
MyService myService = context.getBean("proxyFactoryBean", MyService.class);
myService.myMethod();
}
}
五、运行结果
文章来源地址https://www.toymoban.com/news/detail-598257.html
到了这里,关于spring复习:(39)注解方式的ProxyFactoryBean的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!