1.引入jar包
首先在spring context beans core等jar包基础上引入aop需要的jar包,使用maven的pom导入,具体jar包如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
2. spring配置文件配置自动扫描和切面自动代理
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.ucl"/>
<!-- 自动为切面方法中匹配的方法所在的类生成代理对象。 -->
<aop:aspectj-autoproxy/>
3. 编写切入点类
在切入了点类前面加@Service,使其创建bean
package com.ucl.service;
import com.ucl.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void print() {
System.out.println("userService方法");
}
}
4. 编写切面类
在切面类前面加注解@Component加入到IOC容器,加注解@Aspect成为切面类
@Before中配置表达式,第一个*表示返回值任意,后面的com......表示service包下面的任意类中的任意方法,括号中俩个点表示参数值任意。
package com.ucl.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Aop {
@Before("execution(* com.ucl.service.*.*(..))")
public void before(){
System.out.println("前置增强");
}
}
XML配置实现AOP
1.配置spring的xml文件
<aop:config>
<aop:aspect id="aop" ref="aop">
<aop:pointcut id="cut" expression="execution(* com.ucl.dao.*.*(..))"/>
<aop:before method="before" pointcut-ref="cut"/>
</aop:aspect>
</aop:config>
aop:aspect配置切面,ref引入IOC容器中的切面类
aop:pointcut配置切入点,expression配置表达式
aop:before前置增强
2. 切面类和Service类要加注解加入IOC容器
//切面类加入IOC容器
@Component
public class Aop {
//Service类加入IOC容器
@Service
public class UserService {
3.完成
小问题
spring和spring-mvc整合后要在spring-mvc的位置文件中开启注解扫描
<aop:aspectj-autoproxy/>
kk_image.png