spring_AOP注解入门

来源:互联网 发布:axure8中文破解版 mac 编辑:程序博客网 时间:2024/06/05 18:53

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();    }}

输出结果如下

原创粉丝点击