(一)@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() 方法返回的是同一个实例。
(二)@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();
}
}