Spring AOP中Introduction的使用

Introduction是啥?在Spring中如果有一个已经存在的service,我们想对其进行增强,但是又不想改变其代码,这个时候就可以使用Introduction来处理。具体怎么实现,看下面的详细例子。

引入jar包

 <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>

        <!--spring aop依赖AspectJ-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>

    </dependencies>

新建配置类

@Configuration
@ComponentScan("com.xqc")
@EnableAspectJAutoProxy
public class IntroductionConfig {


}

新建接口OrderInterface并添加say方法

public interface OrderInterface {

    void say();
}

实现类

@Service
public class OrderInterfaceImpl implements OrderInterface{
    @Override
    public void say() {
        System.out.println("say...");
    }
}

新建OrderServiceImpl类,

@Service
public class OrderServiceImpl {

}

可以看出该类中没有任何方法,但是我们又想使用say方法。需要添加切面类,然后使用@DeclareParents注解

@Aspect
@Component
public class IntroductionAspect {

    @DeclareParents(value = "com.xqc.introduction.OrderServiceImpl",defaultImpl = OrderInterfaceImpl.class)
    private OrderInterface orderInterface;

}
value:写需要增强的类,支持表达式
defaultImpl:具体实现增强方法的的类

结果输出


public class TestIntroduction {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IntroductionConfig.class);
            OrderInterface orderInterface = (OrderInterface)context.getBean(OrderServiceImpl.class);
            System.out.println(orderInterface);
            orderInterface.say();

        }
}

 成功调用OrderInterfaceImpl的say方法


工程结构

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架AOP(面向切面编程)是一种重要的特性,它允许开发者在不修改原有代码的情况下,通过横切关注点的方式来增强应用程序的功能。Spring框架提供了强大的AOP支持,下面是Spring使用到的AOP的一些关键概念和用法: 1. 切面(Aspect):切面是一个模块化的单元,它封装了横切关注点和通知(Advice)。在Spring,切面可以是一个普通的Java类。 2. 连接点(Join Point):连接点是在应用程序执行过程可以插入切面的点。在Spring,连接点可以是方法调用、方法执行、异常抛出等。 3. 通知(Advice):通知定义了在连接点上执行的动作。在Spring,有以下几种类型的通知: - 前置通知(Before Advice):在连接点之前执行。 - 后置通知(After Advice):在连接点之后执行,无论连接点是否发生异常。 - 返回通知(After Returning Advice):在连接点正常返回后执行。 - 异常通知(After Throwing Advice):在连接点抛出异常后执行。 - 环绕通知(Around Advice):包围连接点的通知,在连接点前后都可以执行自定义的逻辑。 4. 切点(Pointcut):切点是一个表达式,它定义了哪些连接点将被切面的通知所影响。在Spring,切点可以使用表达式语言(如AspectJ表达式)来定义。 5. 引入(Introduction):引入允许向现有的类添加新的方法或属性。在Spring,引入可以通过AOP来实现。 6. 织入(Weaving):织入是将切面应用到目标对象并创建代理对象的过程。在Spring,织入可以在编译时、类加载时或运行时进行。 Spring框架提供了多种方式来配置和使用AOP,包括基于XML的配置、基于注解的配置和基于Java配置。开发者可以根据具体需求选择适合的方式来使用AOP

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值