切面配置

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

<bean id="userMangerImpl" class="org.teddy.spring.UserManager"/>
<bean id="mySecurityManagerImpl" class="org.teddy.spring.MySecurityManagerImpl"/>
<aop:config proxy-target-class="true">
<aop:aspect id="securityManager" ref="mySecurityManagerImpl">
<aop:pointcut id="flagMethod" expression="execution(* add*(..))||execution(* del*(..))"/>
<aop:before pointcut-ref="flagMethod" method="checkSecurity"/>
</aop:aspect>
</aop:config>
</beans>
### Spring MVC 中 AOP 的配置方法 在 Spring MVC 中实现切面编程(AOP),可以通过 XML 配置或者基于注解的方式完成。以下是具体的配置示例: #### 1. 基于 XML 文件的 AOP 配置 为了使 AOP 功能生效,需要确保所有的配置都放置在 `application-servlet.xml` 或者其他与 Spring MVC 关联的配置文件中[^1]。 ```xml <!-- 组件扫描 --> <context:component-scan base-package="com.example.package" /> <!-- 启用 AspectJ 自动代理 --> <aop:aspectj-autoproxy /> ``` 上述代码片段启用了组件扫描功能并自动创建 AOP 代理对象[^2]。如果未启用 `<aop:aspectj-autoproxy/>`,则可能导致 AOP 切面无法正常工作[^3]。 #### 2. 定义切面类 定义一个带有 `@Aspect` 注解的 Java 类作为切面,并通过 `@Before`, `@AfterReturning`, `@Around` 等注解来指定切入点和通知逻辑。 ```java package com.example.aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Component @Aspect public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("Logging before method execution..."); } } ``` 在此示例中,`LoggingAspect` 是一个切面类,它会在任何匹配的服务层方法执行前打印日志消息。 #### 3. 测试 AOP 配置 确保服务层的方法被调用时触发相应的切面逻辑。例如,在控制器中注入服务实例并调用其方法即可验证效果。 ```java @RestController @RequestMapping("/test") public class TestController { private final MyService myService; public TestController(MyService myService) { this.myService = myService; } @GetMapping("/invoke-service") public String invokeServiceMethod() { myService.performAction(); return "Service invoked successfully."; } } ``` 当访问 `/test/invoke-service` 路径时,应该能够看到控制台输出的日志信息。 --- ### 注意事项 - 如果将 AOP 配置错误地放在了全局上下文文件(如 `applicationContext.xml`)而不是 Spring MVC 特定的配置文件中,则可能会导致 AOP 不起作用。 - 确保项目已引入必要的依赖项,例如 AspectJ 和 Spring AOP 支持库。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值