Spring_007_AOP_Annotation

在Spring中使用AOP的步骤如下:

1、首先在xml文件中添加如下配置:

xmlns:aop="http://www.springframework.org/schema/aop"

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

<?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:context="http://www.springframework.org/schema/context"
       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/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
		<context:annotation-config/>
		<context:component-scan base-package="com.jimmy" />
		<aop:aspectj-autoproxy />

  <bean id="userService" class="com.jimmy.service.UserService" >
     
  </bean>
  

</beans>


 

2、导入aspectj的2个jar包:aspectjrt.jar和aspectjweaver.jar

3、xml文件通过该标签: <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 来告知Spring要使用AOP

4、在切面的类标注@Aspect与@Component,并在方法前标注@Before

package com.jimmy.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {
	@Before("execution(public void com.jimmy.dao.imp.UserOracleDao.add(com.jimmy.model.User))")
	public void logBefore(){
		System.out.println("Log start....");
	}
}

 

Spring在执行的时候通过标签得知要使用AOP,因此找到使用@Aspect标签的类,并将这个类作为切面,而且通过@Before 方法指导在执行UserOracleDao.add方法之前执行logBefore方法(该切面方法必须要使用@Component,否则Spring无法为其初始化,只有都交由Spring来初始化才可以继续使用AOP)。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值