1.pom.xml
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
...其他spring dependency
2.UserService.java
public class UserService {
public String saveUser(String text){
System.out.println("###调用saveUser方法####");
return text;
};
public String update(String text){
System.out.println("###调用update方法####");
return text;
};
public String delete(String text){
System.out.println("###调用delete方法####");
return text;
};
}
3. Advices.java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
//通知者
public class Advices {
//在目标方法之前执行
public void before(JoinPoint joinPoint){
System.err.println("Before ...");
}
//在目标方法之后执行
public void after(JoinPoint joinPoint){
System.err.println("After ...");
}
//在目标方法返回之后执行
public void afterReturning(JoinPoint joinPoint){
System.err.println("afterReturning ...");
}
public void around(ProceedingJoinPoint joinPoint){
System.err.println("around ...");
}
}
4.context.xml
<bean id="userService" class="com.ecs.AOP.UserService" >
</bean>
<bean id="advices" class="com.ecs.AOP.Advices" >
</bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<aop:config proxy-target-class="true" >
<aop:aspect ref="advices" >
<aop:pointcut expression="execution(* com.ecs.AOP.UserService.save*(..) or
execution(* com.ecs.AOP.UserService.update(..)) or
execution(* com.ecs.AOP.UserService.delete(..))" id="pointcut1"/>
<aop:before method="before" pointcut-ref="pointcut1"/>
<aop:after method="after" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
5.Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:servlet-context.xml","classpath:applicationContext.xml"})
@WebAppConfiguration
public class UnitTest {
@Autowired
private WebApplicationContext wac;
@Test
public void test(){
try {
UserService userService = wac.getBean(UserService.class);
String text = userService.saveUser("hello");
System.err.println(text);
} catch (BeansException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}