@SpringBootApplication
@Slf4j
// 指示是否创建基于子类(CGLIB)的代理,而不是创建基于标准Java接口的代理。 默认值是{@code false}。
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringAopApplicationDemo implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(SpringAopApplicationDemo.class, args);
}
// 定义切面,或者直接使用@Component注解
@Bean
public FooAspect fooAspect() {
return new FooAspect();
}
// 有接口实现
@Autowired
LoginService loginService;
// 无接口实现
@Autowired
PlainLoginService plainLoginService;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info(loginService.getClass().toString()); // class io.spring.action.aop.service.impl.LoginServiceImpl$$EnhancerBySpringCGLIB$$d3171a1f
loginService.login();
log.info(plainLoginService.getClass().toString()); // class io.spring.action.aop.service.PlainLoginService$$EnhancerBySpringCGLIB$$5b51dab3
plainLoginService.login();
}
}
@Configuration
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = false)
@Slf4j
public class SpringApplicationDemo {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationDemo.class);
LoginService loginService = context.getBean(LoginService.class); //jdk
PlainLoginService plainLoginService = context.getBean(PlainLoginService.class); // cglib
log.info("jdk class name = {}", loginService.getClass());
log.info("cglib class name = {}", plainLoginService.getClass());
}
@Autowired
private LoginService loginService;
// 定义切面,或者直接使用@Component注解
@Bean
public FooAspect fooAspect() {
return new FooAspect();
}
}
@Configuration
@ComponentScan
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Slf4j
public class SpringApplicationDemo {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationDemo.class);
LoginService loginService = context.getBean(LoginService.class); //jdk
PlainLoginService plainLoginService = context.getBean(PlainLoginService.class); // cglib
log.info("jdk class name = {}", loginService.getClass());
log.info("cglib class name = {}", plainLoginService.getClass());
}
//Bean named 'loginServiceImpl' is expected to be of type 'io.spring.action.aop.service.impl.LoginServiceImpl' but was actually of type 'com.sun.proxy.$Proxy21'
// **AOP代理对象如果使用jdk代理,只能赋值给接口,不能赋值给实现**
//|||焦作市https://henansheng_jiaozuo>>郑州市https://henansheng_zhenzhoushi>>安阳市https://henansheng_anyangshi>>洛阳市https://henansheng_luoyangshi>>x新乡https://henansheng_xinxiangshi|||
// SpringBoot中出于这个考虑,将所有代理对象默认为cglib
@Autowired
private LoginServiceImpl loginService;
// 定义切面,或者直接使用@Component注解
@Bean
public FooAspect fooAspect() {
return new FooAspect();
}
}
河南省_downFile_spring cglib和jdk动态代理
于 2023-05-28 21:37:41 首次发布