spring的aop代理
时间: 2024-01-11 20:20:49 浏览: 41
Spring的AOP代理是通过动态代理实现的。在Spring中,创建Bean实例都是从getBean()方法开始的。在实例创建之后,Spring容器将根据AOP的配置去匹配目标类的类名,看目标类的类名是否满足切面规则。如果满足切面规则,就会调用ProxyFactory创建代理Bean并缓存到IoC容器中。根据目标对象的自动选择不同的代理策略。如果目标类实现了接口,Spring会默认选择JDK Proxy,如果目标类没有实现接口,Spring会默认选择Cglib Proxy,当然,我们也可以通过配置强制使用Cglib Proxy。
下面是一个使用Spring AOP代理的例子:
```java
// 定义一个接口
public interface UserService {
void addUser(String username, String password);
}
// 实现接口
public class UserServiceImpl implements UserService {
@Override
public void addUser(String username, String password) {
System.out.println("添加用户:" + username + ", 密码:" + password);
}
}
// 定义切面
@Aspect
@Component
public class LogAspect {
@Before("execution(* com.example.service.UserService.addUser(..))")
public void beforeAddUser(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
System.out.println("添加用户:" + args[0] + ", 密码:" + args[1]);
}
}
// 配置文件
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl();
}
@Bean
public LogAspect logAspect() {
return new LogAspect();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.addUser("admin", "123456");
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)