基于Annotation的零配置方式--AspectJ

复习一下Spring AOP利用注解的形式,配置一个简单的@Before事前通知

首先定义一个切面,注意添加@Aspect之后,Spring不会对该类进行增强处理,定义@Before事前通知,使用@Before来标注一个方法时,该方法就被定义成事前通知,通常需要指定@Before一个属性值value,该属性值指定一个切入点表达式,在匹配这个表达式的方法执行之前,被定义成事前通知的authority()方法将会先执行。


package org.crazyit.app.advice;

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

//定义一个切面
@Aspect
public class BeforeAdviceTest {
	 
	//匹配org.sun.service.impl包下的所有类的、所有方法的执行作为切入点
	@Before("execution(* org.crazyit.app.service.impl.*.*(..))")
	public void authority(){
		System.out.println("模拟权限检查");
	}
}

定义一个接口,和该接口的实现类


package org.crazyit.app.service;

public interface Person {
	public String sayHello(String name);
	public void eat(String food);
}


package org.crazyit.app.service.impl;

import org.crazyit.app.service.Person;
import org.springframework.stereotype.Component;

@Component()
public class Chinese implements Person {

	@Override
	public String sayHello(String name) {
		return name + "Hello,Spring AOP";
	}
	
	@Override
	public void eat(String food){
		System.out.println("我正在吃:"+food);
	}

}

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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 启用aspectj支持 -->
	<aop:aspectj-autoproxy/>
	
	<context:component-scan base-package="org.crazyit.app.service,org.crazyit.app.advice">
		<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
	</context:component-scan>

	<!--<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
-->
</beans>


最后查看执行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值