导入坐标(pom.xml)
<dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><!--spring和springMVC环境依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.18.RELEASE</version></dependency><!--servlet依赖--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!--spring事务管理依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.18.RELEASE</version></dependency><!--mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><!--spring整合mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency><!--spring整合数据源依赖--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency><!--mysql数据库连接--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!--spring整合Junit依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.18.RELEASE</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!--lombok插件--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.10</version></dependency><!--日志支持--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency></dependencies>
连接点方法(service接口与实现类)
public interface UserService {public void login();
}
@Service
public class UserServiceImpl implements UserService {@Overridepublic void login() {System.out.println("登录操作...");}
}
制作共性功能(通知类与通知,就是基于增强逻辑封装的方法)
public class MyAdvice {public void method(){System.out.println(new Date()+"登录...");}
}
创建切面类(一般都是直接在通知类上使用注解,标识当前类为切面配置类)
定义切入点
绑定切入点与通知关系(切面,在切面中完成切入点和通知的关联,通过注解实现)
//通知类必须配置成Spring管理的bean
@Component
//设置当前类为切面类类
@Aspect
public class MyAdvice {//设置切入点,@Pointcut注解要求配置在方法上方@Pointcut("execution(void com.yaorange.service.impl.UserServiceImpl.login())")public void pt(){}//设置在切入点pt()的方法执行后(不管是否出现异常)运行@After("pt()")public void method(){System.out.println(new Date()+"登录...");}
}
测试类运行代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class TeatAdvice {@Autowiredprivate UserService userService;@Testpublic void login(){userService.login();}}