SSM框架—Spring AOP之基于注解的声明式AspectJ(Demo)

项目结构

XML

<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--自动搜索切面类-->
    <context:component-scan base-package="learning.aop"/>

    <!--启动@AspectJ支持 默认是false-->
    <aop:aspectj-autoproxy expose-proxy="true"/>
</beans>

Person.java

package learning.aop;

import org.springframework.stereotype.Component;

@Component
public class Person {
    public void eat() {
        System.out.println("吃早餐哈");
    }
}

AdivceMethod.java

package learning.aop;

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

@Component
@Aspect
public class AdivceMethod {
    @Before("execution(* learning.aop.Person.*(..))")
    public void beforeEat() {
        System.out.println("吃饭之前先蹦迪");
    }
}

AopTest.java

package learning.aop;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AopTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("/learning/spring/aop.xml");
        Person  person = (Person) context.getBean("person");
        person.eat();
    }
}

 

posted on 2018-12-18 14:53  东子z  阅读(385)  评论(1编辑  收藏  举报

导航