- @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
- @Bean注解为方法级别的注解,通常和使用@Configuration注解的配置类使用,把@Bean写在配置类的方法上。
两者对比
相同点:两者的结果都是为spring容器注册Bean.
不同点:@Component 通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。
@Bean 注解通常是我们在标有该注解的方法中定义产生这个bean的逻辑。
-
@Component的使用
@Component public class Student { private String name = "lkm"; public String getName() { return name; } public void setName(String name) { this.name = name; } }@Bean 需要在配置类中使用,即类上需要加上@Configuration注解
-
@Configuration public class WebSocketConfig { @Bean public Student student(){ return new Student(); } }@Component (@Controller @Service @Respository)作用于类上,只有在我们的SpringBoot应用程序启用了组件扫描并且包含了被注解的类时才有效。通过组件扫描,Spring将扫描整个类路径,并将所有@Component注释类添加到Spring Context,这里有的不足就是会把整个类当成bean注册到spring 容器上,如果这个类中并不是所有方法都需要注册为bean的话,会出现不需要的方法都注册成为bean,这时候必须确保这些不需要的方法也能注册为bean或者在扫描中加filter 过滤这些不需要的bean,否者spring将无法成功启动。
@Bean相对来说就更加灵活了,它可以独立加在方法上,按需注册到spring容器,而且如果你要用到第三方类库里面某个方法的时候,你就只能用@Bean把这个方法注册到spring容器,因为用@Component你需要配置组件扫描到这个第三方类路径而且还要在别人源代码加上这个注解,很明显是不现实的。
@Autowired和@Component是配合使用的
@Component(@Controller、@Service、@Repository):自动创建一个实例并装配到Spring容器中(放到IOC中)
@Autowired:织入(Spring上下文已有实例(已注入IOC,已使用@Component装配过的类),@Autowired只是取一下)
@Autowired说“请给我一个该类的实例,例如,我之前用@Bean注释创建的一个实例进入IOC了”。
@Autowired一般用在变量上,spring容器会自动注入值。
priviate UserService userService;
这篇博客探讨了Spring框架中@Component和@Bean注解的异同。@Component用于标记组件类,通过类路径扫描自动加入Spring容器,而@Bean注解在方法上,允许手动定义bean的创建逻辑。相比@Component,@Bean提供了更细粒度的控制和灵活性,适用于第三方库中类的注册。同时,@Autowired用于依赖注入,从容器中寻找匹配的bean。
1565

被折叠的 条评论
为什么被折叠?



