@Configuration和@Component的区别

每次使用SpringBoot配置我们自定义的类时候
发现有时用@Component有时使用@Configuration
我一度以为看自己定义的类继承的类是否是config包下的,是就用@Configuration不是就使用@Component,
然而最近在看RabbitMQ视频的时候,发现视频里配置类也使用了@Configuration但并没有继承配置类

在这里插入图片描述
于是我就抱着好奇的心给它换成了@Component居然也能运行

我还以为和Rabbit的依赖有关,我又去创了一个只有web的依赖springboot项目

@Configuration
public class User {
    public void hello() {
        System.out.println("你好呀!!!");
    }
}
@Component
public class Role {
    public void hello() {
        System.out.println("不好!!!");
    }
}
@SpringBootTest
class ConfigApplicationTests {
    @Autowired
    private User user;
    @Autowired
    Role role;
    @Test
    void contextLoads() {
        user.hello();
        role.hello();
    }

}

运行结果

在这里插入图片描述
由此总结,可能@Configuration和@Component作用一样。

自己日常的总结也可能是错的,不喜勿喷!

发布了28 篇原创文章 · 获赞 7 · 访问量 8580

猜你喜欢

转载自blog.csdn.net/qq_35953966/article/details/104041707