AOP的配置

<!--aop依赖-->
<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.7.2</version>
</dependency>

实体类
package com.sys.aop;

public class Log {
    public void operationBefore(){
        System.out.println("操作前。。");
    }
    public void operationAfter(){
        System.out.println("操作后。。");
    }
}

<bean id="log" class="com.sys.aop.Log"></bean>
<!--日志aop-->
<!--  config标签定义aop aspect定义切面 pointcut 定义切入点 before和after定义切点前后方法 
(execution(* com.sys.controller.*(..))) 第一个*代表任意类型
 com.sys.controller.*代表包名
 *(..)代表任意方法-->
 <aop:config>
    <aop:aspect ref="log">
        <aop:pointcut
                expression="execution(* com.sys.controller.*.*(..))"
                id="chiefPointCut" />
        <aop:before method="operationBefore" pointcut-ref="chiefPointCut" />
        <aop:before method="operationAfter" pointcut-ref="chiefPointCut" />
    </aop:aspect>

</aop:config>
### 关于AOP配置的方法 #### 使用注解的方式进行Spring AOP配置 在现代的Spring应用程序开发环境中,采用注解配置已经成为了一种趋势。这种方式不仅简化了配置过程,而且增强了Java代码中的集成度,提高了可读性和维护性[^2]。 为了启用基于注解的AOP支持,在项目中应当确保已导入`spring-aop`依赖项以及任何必要的第三方库。接着可以在类上应用特定的注解来定义切面逻辑: - `@Aspect`: 定义一个切面类; - `@Pointcut`: 描述匹配哪些连接点的位置表达式; - `@Before`, `@AfterReturning`, `@Around`, `@AfterThrowing`, 和 `@After`: 表示不同类型的通知行为; ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class LoggingAspect { @Before("execution(* com.example.service..*(..))") public void logServiceMethods() { System.out.println("Executing service method"); } } ``` 上述例子展示了如何创建简单的日志记录切面,它会在每次调用服务层方法之前打印一条消息。 #### 利用XML文件来进行AOP设置 对于偏好或者受限于旧版本框架的情况,也可以通过XML方式进行AOP配置。这通常涉及到向Spring容器注册自定义的Advisor对象或是直接利用`<aop:config>`标签完成更复杂的场景设定[^4]。 以下是使用XML配置的一个基本实例: ```xml <aop:config> <!-- 配置具体的切入点 --> <aop:pointcut id="serviceOperations" expression="execution(* com.example.service.*(..))"/> <!-- 将通知与切入点关联起来 --> <aop:before pointcut-ref="serviceOperations" method="logServiceMethodCall"/> </aop:config> <!-- 声明切面bean并指定其包含的方法作为通知 --> <bean id="loggingAspect" class="com.example.LoggingAspect"> <property name="loggerName" value="SERVICE_LOGGER"/> </bean> ``` 此片段说明了怎样借助XML声明式的语法建立相同的日志记录机制。 #### 在Spring Boot环境下快速启动AOP功能 当涉及Spring Boot时,得益于自动装配特性,只需添加相应的starter包即可轻松激活AOP能力,并可通过编写带有适当注解的组件来自动生成所需的代理实例[^3]。 例如,在pom.xml中加入如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 之后按照前述提到的注解模式构建自己的切面类就可以立即生效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值