AOP中使用的注解 @Service @Aspect @component

@Service标注将这个类在扫描时注册到Spring容器管理

@Aspect是将该类声明为切面类

@component把该类实例化放入到spring容器中,

@五种增强("execution(public 返回值 地址.*(..))")

AOP实现的大致流程即为

将目标方法的类通过@Service注册到Spring容器管理,以便之后生成代理对象

通过@Aspect声明切面类,然后@component放入spring容器中

通过@五种增强("execution(public 返回值 地址.*(..))")建立切面

在ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("app.xml");
代码执行时创建IOC容器,@Service标注的类中方法与@Aspect@component标注的切面类中切入点表达式匹配,默认情况下IOC自动为@Service标注的类创建代理类并创建相应的代理对象,之后通过applicationContext.getBean(class);得到该类即可操作。

在 Spring AOP 中启用 @Aspect 注解,你需要在以下几个步骤中操作: 1. **添加依赖**:确保你的项目依赖了 Spring AOP 相关的库,例如在 Maven 项目的 `pom.xml` 文件中添加 `<spring-aop>` 或 `<aop:aspectj-autoproxy>` 标签。 ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> ``` 或者对于基于 XML 配置的方式: ```xml <aop:config> <!-- 其他配置 --> <aop:aspect id="myAspect" ref="com.example.MyAspect"> <!-- aspect 类路径 --> </aop:aspect> </aop:config> ``` 2. **编写 @Aspect 类**:创建一个实现了 `@Aspect` 注解的 Java 类,该类中包含 `@Before`、`@After`、`@Around` 等通知注解的切入点方法。 ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect @Component public class MyAspect { @Before("execution(* com.example.service.MyService.*(..))") public void beforeAdvice(JoinPoint joinPoint) { // 执行前的操作 } } ``` 3. **配置扫描**:在 Spring 的配置文件中,使用 `@ComponentScan` 或者 `<context:component-scan>` 注入 `@Aspect` 注解的类。 ```xml <context:component-scan base-package="com.example"> <!-- 如果需要扫描特定包中的 aspects --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> ``` 4. **启动应用**:启动 Spring 应用,这时 Spring AOP 就会处理包含 @Aspect 注解的切面。 现在,你应该可以在目标类(如 service 层)中的方法上看到切面的通知效果了。如果你仍然遇到问题,可以检查配置文件、依赖及代码逻辑,看看是否有其他冲突或者遗漏的地方。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值