- /**要侵入的接口*/
- package com.book.service;
- public interface Monitorable {
- public void setMonitorActive(Boolean flage);
- }
- package com.book.serviceImpl;
- import com.book.entity.User;
- /**目标类*/
- public class UserServiceImpl {
- public User findByName(String name) {
- // TODO Auto-generated method stub
- System.out.println("进入了service层了哦!!!");
- return new User(name,"26");
- }
- }
- /**增强*/
- package com.book.aop;
- import org.aopalliance.intercept.MethodInvocation;
- import org.springframework.aop.support.DelegatingIntroductionInterceptor;
- import com.book.service.Monitorable;
- public class PerformanceMonitor extends DelegatingIntroductionInterceptor implements Monitorable{
- private ThreadLocal<Boolean> laosn=new ThreadLocal<Boolean>();
- public void setMonitorActive(Boolean flage) {
- // TODO Auto-generated method stub
- laosn.set(flage);
- }
- public Object invoke(MethodInvocation mi) throws Throwable{
- Object obj=null;
- if(laosn.get()!=null&&laosn.get()){
- System.out.println("-------------哈哈!骚年!你被织入了接口了----------开始-----");
- obj=super.invoke(mi);
- System.out.println("-------------哈哈!骚年!你被织入了接口了----------结束-----");
- }else {
- obj=super.invoke(mi);
- }
- return obj;
- }
- }
- @Controller
- public class TianController {
- @Resource(name="userServiceProxyfactorybean")
- private UserServiceImpl userServiceProxyfactorybean;
- @RequestMapping("/tian2")
- public String tian2(){
- /**转换成侵入接口然后再调用接口方法改变行为*/
- Monitorable mo=(Monitorable)userServiceProxyfactorybean;
- mo.setMonitorActive(true);
- User user=proxyfactorybean.findByName("zhangtian");
- return "user/index";
- }
- }
- /**最后配置applicationContext.xml*/
- <!-- 此配置演示了 引介切点 -->
- <bean id="performancemonitoradvice" class="com.book.aop.PerformanceMonitor"></bean>
- <bean id="userserviceTarget" class="com.book.serviceImpl.UserServiceImpl"></bean>
- <bean id="userServiceProxyfactorybean" p:interfaces="com.book.service.Monitorable" p:interceptorNames="performancemonitoradvice" p:target-ref="userserviceTarget" p:proxyTargetClass="true"class="org.springframework.aop.framework.ProxyFactoryBean"/>
- //该片段来自于http://www.codesnippet.cn/detail/2208201715237.html
来源: http://www.codesnippet.cn/detail/2208201715237.html