Maven工程基于XML配置开发Spring AspectJ
1 配置Maven工程的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>day08_proxy</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
</dependencies>
</project>
2 定义目标对象(被代理对象 )
package com.itheima.aop_xml;
public interface UserService {
void login();
}
package com.itheima.aop_xml;
public class UserServiceImpl implements UserService {
public void login() {
System.out.println("用户登录了...");
}
}
3 创建一个增强类(代理对象)
package com.itheima.aop_xml;
public class Advice {
public void writeLog() {
System.out.println("增强功能... 记录日志....");
}
public void checkPower() {
System.out.println("增强功能... 校验权限....");
}
}
4 创建bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.itheima.aop_xml.UserServiceImpl" />
<bean id="advice" class="com.itheima.aop_xml.Advice" />
<aop:config>
<aop:pointcut id="point01" expression="execution(* *..login(..))" />
<aop:aspect ref="advice">
<aop:after method="writeLog" pointcut-ref="point01" />
</aop:aspect>
</aop:config>
</beans>
5 整合spring-test进行测试
package com.itheima.aop_xml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void login() {
userService.login();
}
}