AspectJ实现AOP(注解方式)

本文介绍了如何利用AspectJ的注解方式来实现AOP,相比XML配置更加便捷。通过@Aspect、@Component和@Before等注解,简化了AOP的配置过程,并提供了登录场景的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇讲到了使用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");
	}
}
最后,看测试结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值