最为简单的AOP示例

创建Agernt

public class Agent {
    public void speak(){
        System.out.println("Hello");
    }
}

创建代理

public class AgentDecorator implements MethodInterceptor {
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("James");
        Object result = methodInvocation.proceed();
        System.out.println("!");
        return result;
    }
}

创建Demo示例

public class AgentAopDemo {
    public static void main(String[] args) {
        Agent target = new Agent();
        //ProxyFactory 创建目标代理对象
        ProxyFactory proxyFactory = new ProxyFactory();
        //织入通知
        proxyFactory.addAdvice(new AgentDecorator());
        //织入目标
        proxyFactory.setTarget(target);
        //生成代理对象
        Agent agent = (Agent) proxyFactory.getProxy();
        target.speak();
        System.out.println("---");
        agent.speak();
    }
}

当您使用Spring Boot AOP(面向切面编程)时,可以通过创建切面、定义切点和编写通知来实现横切关注点的功能。下面是一个简单示例,演示如何使用Spring Boot AOP编程: 1. 首先,确保在pom.xml文件中添加了`spring-boot-starter-aop`依赖项: ```xml<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 2. 创建一个切面类`LoggingAspect`,使用`@Aspect`注解标记为切面: ```javaimport org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect@Componentpublic class LoggingAspect { @Before("execution(* com.example.demo.*.*(..))") public void beforeAdvice() { System.out.println("Before executing the method..."); } } ``` 在上述代码中,`@Before`注解指定了在执行匹配切点的方法之前要执行的通知。`execution(* com.example.demo.*.*(..))`是一个切点表达式,它表示匹配`com.example.demo`包下的所有类的所有方法。 3. 创建一个简单示例类`DemoController`: ```javaimport org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestControllerpublic class DemoController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } } ``` 4. 运行Spring Boot应用程序,您将看到在访问`/hello`接口时,控制台将输出`Before executing the method...`的信息。 这个示例展示了一个简单的切面,它在执行匹配切点的方法之前打印出一条消息。您可以根据自己的需求编写更复杂的切面和通知。 希望这个示例能帮助您理解如何在Spring Boot中使用AOP编程。如果您有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值