一、定義接口
package cn.edu.tju.study.service;
public interface MyService {
void myMethod();
}
二、定義實現(xiàn)類:
package cn.edu.tju.study.service;
public class MyServiceImpl implements MyService{
@Override
public void myMethod() {
System.out.println("hello world...");
}
}
三、定義配置類,配置業(yè)務(wù)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并使用文章來源:http://www.zghlxwxcb.cn/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();
}
}
五、運行結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-598257.html
到了這里,關(guān)于spring復(fù)習:(39)注解方式的ProxyFactoryBean的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!