如果在编写的config类上添加@Component与@Configuration注解,你如果在别的地方进行注入的时候,都会能够完成注入的功能。点开@Configuration注解,发现本质也是@Component。但是仔细发现,注入后得到的对象是不一样的。@Component得到不是同一个对象,@Configuration得到的是同一个对象。

下面示例:

@Configuration
//@Component
public class MyBeanConfig {
    @Bean
    public Org org() {
        return new Org();
    }

    @Bean
    public Unit unit() {
        Unit unit = new Unit();
        unit.setOrg(org());
        return unit;
    }

}

Spring Boot @Component与@Configuration的区别

  

//@Configuration
@Component
public class MyBeanConfig {
    @Bean
    public Org org() {
        return new Org();
    }

    @Bean
    public Unit unit() {
        Unit unit = new Unit();
        unit.setOrg(org());
        return unit;
    }

}

Spring Boot @Component与@Configuration的区别

相关文章:

  • 2023-04-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-28
  • 2023-03-02
  • 2023-04-07
  • 2021-10-09
  • 2022-12-23
猜你喜欢
  • 2022-03-05
  • 2022-12-23
  • 2021-06-25
  • 2021-12-12
  • 2021-06-11
  • 2022-12-23
相关资源
相似解决方案