spring_AOP注解入门

本文介绍了AOP(面向切面编程)的概念及其在Spring框架中的应用。通过具体实例展示了如何利用AOP进行代码增强,包括导入所需jar包、配置XML约束、启用AOP支持、使用注解等方式。

AOP简介

AOP面向接口编程,可以说AOP是面向对象编程没错,但是如果需要更准确的答案,AOP是在(OOP)面向对象编程的基础扩展和优化的,

使用步骤如下

1.导入AOP需要的jar包以及联盟包,如果没有的话可以在资源里下载,

jar包如下
1. aop联盟包
2. aspectJ实现包
3. spring-aop-xxx.jar
4. spring-aspect-xxx.jar

2.导入约束

<?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:context="http://www.springframework.org/schema/context" 
        xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

</beans>

3.在注解里打开AOP开关

<!--开启IOC注解扫描,为了使用IOC获取对象,所以开启扫描-->
    <context:component-scan base-package="cn.itcast"/>

    <!--使用切面注解-->
    <aop:aspectj-autoproxy />

4.在类里上打注解

创建一个被加强类 ,我们加强eat方法

@Component("p")
public class Person {
    public void eat(){
        System.out.println("人在吃");
    }
}

//创建一个提供加强方法的类

@Aspect  //定义切面 ,不要少了该注解
public class Eat {

    //设置该方法为加强方法,前置增强
    @Before("execution(* cn.itcast.aop.Person.eat(..))")  //切入点表达试
    public void Add(){
        System.out.println("加鸡腿");
    }
}
创建测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Autowired
    Person p;

    @Test
    public void Test_01(){
      p.eat();
    }
}

输出结果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值