@Aspect注解

/ Spring / 没有评论 / 384浏览

在这篇中我们将通过@Aspect注解来创建一个切面,以此来演示@Aspect注解的基本使用。

@Aspect
public class UserServiceAspect {

@Before("execution(* register(..))")
public void beforeRegister() {
TransactionManager.beginTransaction();
}

}
public class TransactionManager {

public static void beginTransaction() {

System.out.println("开启事物");
}

public static void commit() {

System.out.println("提交事物");
}
}
public interface IUserService {

public void login(String username, String password);

public void register(String username, String nickName, String password);
}
public class UserServiceImpl implements IUserService {

public void login(String username, String password) {
System.out.println(String.format("用户登陆: username: %s password: %s", username, password));
}

public void register(String username, String nickName, String password) {
System.out.println(String.format("用户注册: username: %s nickName: %s password: %s", username, nickName, password));
}

}
@Test
public void test() {
IUserService target = new UserServiceImpl();
AspectJProxyFactory factory = new AspectJProxyFactory();
factory.setTarget(target);

factory.addAspect(UserServiceAspect.class);

IUserService userService = factory.getProxy();

userService.register("admin", "吉林乌拉", "jilinwula");
userService.login("admin", "jilinwula");
}
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户登陆: username: admin password: jilinwula

下面我们通过xml的方式创建代理类。

<bean id="userService" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean class="com.jilinwula.spring.annotation.UserServiceAspect"/>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
IUserService userService = applicationContext.getBean("userService", IUserService.class);
userService.register("admin", "吉林乌拉", "jilinwula");
userService.login("admin", "jilinwula");
}
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户登陆: username: admin password: jilinwula

虽然上面的配置非常简单,但是spring为aop提供了命名空间,通过命名空间可以更方便的为我们自动创建代理。

<bean id="userService" class="com.jilinwula.spring.aop.UserServiceImpl"/>
<bean class="com.jilinwula.spring.annotation.UserServiceAspect"/>
<aop:aspectj-autoproxy/>
开启事物
用户注册: username: admin nickName: 吉林乌拉 password: jilinwula
用户登陆: username: admin password: jilinwula