Spring AOP 创建Advice 基于Annotation

本文详细介绍了如何使用Spring AOP和AspectJ实现方法调用前后的日志记录功能。通过具体的Java代码示例,展示了如何定义切入点、前置通知和后置通知,以及如何在Spring配置文件中启用AspectJ自动代理。

 

public interface IHello {
  public void  sayHello(String str);
}
public class Hello implements IHello {

	@Override
	public void sayHello(String str) {
		// TODO Auto-generated method stub
	   System.out.println("你好"+str);
	}

}

  

aspectBean.java

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

//引入Aspect注解,声明切面
@Aspect
public class aspectBean {
	//定义为切入点
	@Pointcut("execution(* hello.*(..))")
	public void log() {
		
	}
	@Before(value="log()") //在切入点之前执行
	public void startLog()
	{
		System.out.println("开始记录");
	}
	@After(value="log()") //在切入点之后执行
	public void endLog()
	{
		System.out.println("结束记录");
	}
}

  applicationContext.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
	
	<!-- 启动aspectj -->
	<aop:aspectj-autoproxy/>
	<bean id="apbean" class="com.pb.aspectBean"></bean>
	<bean id="he" class="com.pb.Hello"></bean>
</beans>

  Maintest文件:

public static void main(String[] args) {
		// TODO Auto-generated method stub
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        IHello hello=(IHello)context.getBean("he");
        hello.sayHello("访客");
	}

  执行:

 

转载于:https://www.cnblogs.com/schangxiang/p/11149067.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值