上一篇讲到了使用xml配置方式来实现AOP,相对于xml配置方式,使用注解方式用起来会更方便一点,下面就来实现以下如何使用注解方式来实现AOP。
pom.xml和上一篇一致,不再赘述。
先看Login.java:
package userService;
import org.springframework.stereotype.Component;
@Component
public class Login {
public void login(String userName){
System.out.println("用户"+userName+"登录了");
}
}
再看LoginService.java
package userService;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoginService {
@Before("execution(* userService.Login.*(..))")
public void before(){
System.out.println("用户请求登录,时间为:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
format(new Date()));
}
@After("execution(* userService.Login.*(..))")
public void after(){
System.out.println("用户请求登录结束,时间为:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
format(new Date()));
}
}
@Aspect,@Compoment,@Before这些注解相信都顾名思义,比较简单易懂。
接下来看测试类:
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import userService.Login;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class MyTestCase {
@Autowired
public ApplicationContext applicationContext;
@Test
public void testAop(){
Login login = (Login)applicationContext.getBean("login");
login.login("JACK");
}
}
最后,看测试结果: