@compoent 与@bean的区别

@compoent注解是类上的注解,@bean是方法上的注解,需要加@configuration注解,如果不加就不能反回单例的实例,每次返回都是创建新的实例。方法拦截没有cglib代理。

@bean比@compoent注解更灵活,它可以按需求返回代理对象。

@compoent是@service,@controller等注解的副注解。

@bean是导入第三方类时的注解。

 

@Configuration
public class AppConfig {
@Bean
public ServiceA serviceA() {
return new ServiceA();
}

@Bean
public ServiceB serviceB() {
// 这里调用的是 Spring 增强后的 CGLIB 代理方法
// 会返回单例的 ServiceA(即使多次调用)
return new ServiceB(serviceA());
}
}

 

image

 

posted @ 2026-01-11 15:41  人在代码在  阅读(2)  评论(0)    收藏  举报