spring 装配aop对象
时间: 2023-07-04 17:04:28 浏览: 43
在 Spring 中,可以通过配置文件或注解的方式来装配 AOP 对象。下面是两种常用的方式:
1. 配置文件方式
首先,在 Spring 的配置文件中定义切面和切点:
```xml
<aop:config>
<aop:aspect id="loggingAspect" ref="loggingService">
<aop:pointcut id="loggingPointcut" expression="execution(* com.example.service.*.*(..))" />
<aop:before pointcut-ref="loggingPointcut" method="logBefore" />
<aop:after pointcut-ref="loggingPointcut" method="logAfter" />
</aop:aspect>
</aop:config>
```
上面的配置定义了一个名为 loggingAspect 的切面,它引用了一个名为 loggingService 的 bean。切点使用了表达式来匹配 com.example.service 包中的所有方法。在切点之前和之后,将分别调用 logBefore 和 logAfter 方法。
接下来,在 Spring 的配置文件中定义 bean:
```xml
<bean id="loggingService" class="com.example.service.LoggingService" />
```
这里定义了一个名为 loggingService 的 bean,并指定了它的类为 com.example.service.LoggingService。
2. 注解方式
首先,在切面类上添加 @Aspect 注解:
```java
@Aspect
@Component
public class LoggingAspect {
...
}
```
然后,在切面类中定义切点和通知:
```java
@Pointcut("execution(* com.example.service.*.*(..))")
private void loggingPointcut() {}
@Before("loggingPointcut()")
public void logBefore() {}
@After("loggingPointcut()")
public void logAfter() {}
```
最后,在目标类上添加 @Component 注解:
```java
@Component
public class MyService {
...
}
```
这里定义了一个名为 MyService 的 bean,并指定了它的类为 com.example.service.MyService。在切面中使用 @Pointcut 注解来定义切点,然后使用 @Before 和 @After 注解来定义通知。在目标类上添加 @Component 注解,让 Spring 自动扫描并装配 bean。