您的位置:首页 > 编程语言 > Java开发

ITCAST视频-Spring学习笔记(使用Spring的注解方式实现AOP入门)

2009-02-17 21:42 1311 查看
感谢ITCAST发布的免费视频

使用Spring进行面向切面(AOP)编程

要进行AOP编程,首先我们要在Spring的配置文件中引入aop命名空间:

<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

xsi:schemaLocation=”http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springramework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-2.5.xsd”>

</beans>

spring提供两种切面使用方式,实际工作中我们可以选用其中一种:

基于XML配置方式进行AOP开发

基于注解方式进行AOP开发

基于注解方式声明切面

首先启动对@AspectJ注解的支持(蓝色部分):

<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

xsi:schemaLocation=”http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springramework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-2.5.xsd”>

<aop:aspectj-autoproxy/>

</beans>

@Aspect

public class MyInterceptor {

@Pointcut("execution (* cn.service.impl.PersonServiceBean.*(..))")

public void anyMethod() {} //declare a pointcut

@Before("anyMethod()") //declare a before advice, parameter is the name of the pointcut

public void doAccessCheck() {

System.out.println("before advice");

}

}

比较奇怪的是使用方法作为切入点名称

配置文件:

<?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"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

<bean id="myInterceptor" class="cn.service.MyInterceptor"></bean>

<bean id="personService" class="cn.service.impl.PersonServiceBean"></bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: