pom.xml添加依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
切面代码
/**
* 切面代码
*/
@Aspect
@Component
public class Advice {
@Before("execution(* com.msb.SpringAop.UserServiceImpl.add*(..))")
public void check(){
System.out.println("权限检查....");
}
@After("execution(* com.msb.SpringAop.UserServiceImpl.add*(..))")
public void log(){
System.out.println("日志记录....");
}
}
业务代码
/**
* 业务代码
*/
public interface UserService {
//添加
void add() throws Exception;
//删除
void del() throws Exception;
}
接口实现类
/**
* 接口实现类
* @Service注解如果没有明确设置id值,那默认的id值为类名首字母小写
*/
@Service
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--扫描指定路径,自动注入注解-->
<context:component-scan base-package="com.msb"/>
<!--自动为Spring容器中那些配置@aspectJ切面的bean创建代理-->
<aop:aspectj-autoproxy/>
</beans>
测试类
public class AopTest {
@Test
public void test() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContextAnnotation.xml");
UserService service = (UserService)app.getBean("userServiceImpl");
service.add();
service.del();
}
}
运行结果(这里在配置是文件中我们只针对了add方法前后织入了通知)