pom.xml添加依赖
<!--注解式声明切面-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
切面代码
/**
* 切面代码
*/
public class Advice {
public void check(){
System.out.println("权限检查....");
}
public void log(){
System.out.println("日志记录....");
}
}
业务代码
/**
* 业务代码
*/
public interface UserService {
//添加
void add() throws Exception;
//删除
void del() throws Exception;
}
接口实现类
/**
* 接口实现类
*/
public class UserServiceImpl implements UserService{
public void add() throws Exception {
System.out.println("添加成功....");
}
public void del() throws Exception {
System.out.println("删除成功....");
}
}
applicationContext.xml
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!--创建业务实现类对象-->
<bean id="service" class="com.msb.SpringXml.UserServiceImpl"/>
<!--创建切面类对象-->
<bean id="advice" class="com.msb.SpringXml.Advice"/>
<!--进行动态织入-->
<!--proxy-target-class默认:false,jdk动态代理;true,cdlib动态代理-->
<aop:config proxy-target-class="false">
<!--声明切面对象-->
<aop:aspect ref="advice">
<!--定义切点-->
<aop:pointcut id="addpointcut" expression="execution(* com.msb.SpringXml.UserServiceImpl.add*(..))"/>
<!--定义前置通知-->
<aop:before method="check" pointcut-ref="addpointcut"/>
<!--定义后置通知-->
<aop:after method="log" pointcut-ref="addpointcut"/>
</aop:aspect>
</aop:config>
</beans>
测试类
public class AopTest {
@Test
public void test() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContextXml.xml");
UserService service = (UserService)app.getBean("service");
service.add();
service.del();
}
}
运行结果(这里在配置是文件中我们只针对了add方法前后织入了通知)