Spring AOP——注解和XML

注解
声明一个切点(注解)
@Component//相当于XML中的<bean>
public class EatLemon implements Eat {
    /**
     * 通过@Pointcut注解定义切入点表达式
     */
    @Pointcut("execution(* com.lanou3g.spring.eat.EatLemon.*(..))")
    public String eat() {
        String dd ="吃了柠檬,我酸了";
        System.out.println(dd);
        return dd;
    }
声明一个切面和通知(注解)

@Aspect//定义一个切面
@Component
public class First {
    //指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式
    @Around("execution(* com.lanou3g.spring.eat.EatLemon.*(..))")
    public void look(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("看见某些东西");

        //调用目标方法
        Object retVal = joinPoint.proceed();

        System.out.println("你呢");
    }
}
入口类(注解)
/**
 * 入口类
 */
//相当于Xml中的<beans>
@Configuration
//扫描路径下的注解
@ComponentScan( basePackages = "com.lanou3g.spring.eat")
//开启对AOP相关注解的处理
@EnableAspectJAutoProxy
public class AppByAnnotation {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppByAnnotation.class);
        Eat el =  ctx.getBean(Eat.class);
        el.eat();
    }
}
控制台输出结果(注解)

在这里插入图片描述

XML

现在XML中定义目标类

<!--    原本要执行的代码-->
    <bean id="eat" class="com.lanou3g.spring.eat.EatLemon"/>
定义一个切面类
<!--    切面类-->
    <bean id="aspect" class="com.lanou3g.spring.eat.First"/>
定义切点和通知
<!--    切面类-->
    <bean id="aspect" class="com.lanou3g.spring.eat.First"/>
    <aop:config>
        <aop:pointcut id="first" expression="execution(* com.lanou3g.spring.eat.EatLemon.*(..))"/>
        <aop:aspect ref="aspect">
<!--           环绕通知可以终止目标方法,环绕通知目标方法前后做事的通知 -->
            <aop:around method="look" pointcut-ref="first"/>
        </aop:aspect>
    </aop:config>
入口类(xml)
/**
 * XML
 */
public class App {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Eat el =  ctx.getBean(Eat.class);
        el.eat();
    }
}

控制台结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值