Spring动态代理,aop 注解实现aop

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop"      
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context 

http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

 <aop:aspectj-autoproxy/> 

</beans>

上面红色的事关于spring动态代理的aopxml配置选项,必须要填写

配置完毕后,导入jar包

就可以使用注解实现aop

代码结构


代码样例

dao层

package com.leige.dao;


import org.aspectj.lang.annotation.Aspect;




public interface PersonDao {
public void add();
}

dao层实现

package com.leige.daoimpl;
import org.springframework.stereotype.Repository;


import com.leige.dao.PersonDao;
@Repository("personDao")
public class PersonDaoImpl1 implements PersonDao{


public void add() {
// TODO Auto-generated method stub
System.out.println("leige我是add方法");

}

}

service层

package com.leige.service;


import javax.annotation.Resource;


import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;


import com.leige.dao.PersonDao;
@Service("personService")
public class PersonService {
private PersonDao dao=null;
public PersonDao getDao() {
return dao;
}
@Resource(name="personDao")
public void setDao(PersonDao dao) {
this.dao = dao;
}

}


动态代理拦截

package com.leige.interceptor;


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Repository;


@Aspect
@Repository("myInterceptor")
public class MyInterceptor {
@Pointcut("execution (* com.leige.daoimpl.PersonDaoImpl1.*(..)) ")
public void fun(){}//定义切入点
@Before("fun()")
public void before(){
System.out.println("磊哥无敌");
}
@After("fun()")
public void after(){
System.out.println("leigezuishuai");
}
}


测试类

package com.leige.junit;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.leige.service.PersonService;


import sun.awt.AppContext;


public class PersonTest{
@Test
public void fun(){
ApplicationContext app=new ClassPathXmlApplicationContext("beans.xml");//读取配置文件
PersonService per=(PersonService) app.getBean("personService");
per.getDao().add();
}
}

测试结果


所需jar包


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值