@SpringBootConfiguration ,@Configuration , @Component

(一)@Configuration:

先给一个简单的示例代码:

@Configuration
public class MyBeanConfig {

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country());
    }

}

相信大多数人第一次看到上面 userInfo() 中调用 country() 时,会认为这里的 Country 和上面 @Bean 方法返回的 Country 可能不是同一个对象,因此可能会通过下面的方式来替代这种方式:

@Autowired
private Country country;

实际上不需要这么做(@Configuration使用cglib 动态代理),直接调用 country() 方法返回的是同一个实例。因为@Configuration会检测country是否注入,如果有注入那就在userInfo的时候直接拿过来用就行,但是componet就不会检查,所以就相当于两个country实例,那实际上肯定会报错,因为不允许出现相同的两个实例。如果类上没有注解这个时候也是注入两个实例也是会报错不允许出现相同的两个实例。

(二)@Component:

@Component 注解并没有通过 cglib 来代理@Bean 方法的调用,因此像下面这样配置时,就是两个不同的 country。

作为同一个实例必须加:

  @Autowired
  private Country country;
@Component
public class MyBeanConfig {

    @Autowired
    private Country country;

    @Bean
    public Country country(){
        return new Country();
    }

    @Bean
    public UserInfo userInfo(){
        return new UserInfo(country);
    }

}

(三)@SpringBootConfiguration:

@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
(springboot推荐用@SpringBootConfiguration)

(四)@SpringBootConfiguration ,@Configuration , @Component 共同点:
声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。

Bean在当前类内:
如上代码展示。

Bean不在当前类:
直接在启动类内@Bean

@Component
public class MyHealthIndicator implements HealthIndicator{

    private int healthIndicatorErrorCount;

    private int healthIndicatorCount;

    private boolean hasError=false;

    @Override
    public Health health(){
        if(!hasError){
            healthIndicatorCount++;
           //每检测5次,就返回DOWN
            if(healthIndicatorCount%5==0){
                hasError=true;
            }
        }else{
            //DOWN计数10次就UP
            healthIndicatorErrorCount++;
            if(healthIndicatorErrorCount>10){
                hasError=false;
                healthIndicatorErrorCount=0;
            }
        }

        if(hasError){
            return new Health.Builder(Status.DOWN).build();
        }
        return new Health.Builder(Status.UP).build();
    }
}
public class ProductionApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProductionApplication.class, args);
    }

    /**
     * @Author LJ
     * @Description 自定义健康检查
     * @Date 23:02 2020/2/25
     * @Param []
     * @return com.springcloud.production.healthyconfig.MyHealthIndicator
     **/
    @Bean
    public MyHealthIndicator myHealthIndicator(){
        return new MyHealthIndicator();
    }

}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值