spring注解方式实现AOP的前置通知

spring面向切面(AOP)编程,spring的配置文件中需要引入AOP命名空间:
<?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">
</beans>
spring框架进行AOP编程的时候,spring提供了两种切面声明方式,
1、基于XML配置的方式进行AOP开发。
2、基于注解方式进行AOP开发。
<!--
打开配置项,这个配置项是对@Aspectj这个注解进行支持 注解本身是不能干活的,注解之所以能干活是

因为后面有处理器对其进行处理
这个配置相当于我们将要使用的@Aspectj注解提供了解析的功能
-->
<aop:aspectj-autoproxy />

1、新建业务bean用于测试,PersonService.java
package com.sample.service;

public interface PersonService {
public String getPersonName(Integer Id);

public void save(String userName);

public void update(String userName, Integer Id);
}
2、PersonServiceBeean.java
package com.sample.service.impl;

import com.sample.service.PersonService;

public class PersonServiceBean implements PersonService {

@Override
public String getPersonName(Integer Id) {
System.out.println("我是getPersonName()方法");
return "XXX";
}

@Override
public void save(String userName) {
System.out.println("我是save()方法");
}

@Override
public void update(String userName, Integer Id) {
System.out.println("我是update()方法");
}

}
3、基于注解方式的声明切面
package com.sample.service;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class MyInterceptor {

@Pointcut("execution (* com.sample.service.impl.PersonServiceBean..*.*(..))")
private void anyMethod() {
}// 声明一个切入点

@Before("anyMethod()")
public void doAccessCheck(String name) {
System.out.println("前置通知:" + name);
}

}

4、一定要将业务bean和切面配置在spring容器中(applicationContext.xml)中、也可以自动扫描
<bean id="myInterceptor" class="com.sample.service.MyInterceptor" />
<bean id="personService"
class="com.sample.service.impl.PersonServiceBean">
</bean>
这里也看采用spring的自动扫描交由spring容器管理bean
<context:component-scan base-package="com.sample.*"/>


@Test public void interceptorTest() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save("jack");
}


前置通知:jack
我是save()方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值