<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包