SpringBoot配置类和配置文件

1.@Configuration+@Bean

@Configuration代表这是一个配置类(底层也是一个组件@Component),而在这个配置类中的方法(一定有返回对象)使用@Bean,表示需要注入到spring容器中的bean,其中方法名为bean的默认名称,也可以设置bean的名称

@Configuration
public class AnsyConfig {

    @Bean(name="asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(CommonConstant.THREE);
        //最大线程数
        executor.setMaxPoolSize(CommonConstant.TWENTY);
        //非核心线程闲置超时时长
        executor.setKeepAliveSeconds(CommonConstant.THREE_HUNDRED);
        //队列长度
        executor.setQueueCapacity(CommonConstant.FIFTY);
        //线程前缀
        executor.setThreadNamePrefix("apply-asynnotify-");
        //配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

2.@Configuration+@Value

public class RabbitMqConfig {

    @Value("${server.port}")
    private String port;
}

可以读取配置文件的属性,这个只是将配置文件的属性读取到该配置类中进行使用。@Value通常是使用在属性之上,缺点:一个一个读取,开发繁琐 优点:精准指定所需要的属性,当所需读取的配置文件的属性少时适用

3.@ConfigurationProperties+@Configuration/@Component

/**
 * @author jwdstef
 */
@Data
@Component
@ConfigurationProperties(prefix = "ocr")
public class OcrProperties implements Serializable {
    private Boolean isEnable;//是否开启
    private String url;
    private String ocrCardUrl;
}

@ConfigurationProperties读取配置文件的属性,使用@Configuration/@Component只是为了让读取的这个类注入到spring容器中,方便使用,当然这种类多的时候,每个类都使用了@Configuration/@Component好像显得实在重复工作,因此引入了@@EnableConfigurationProperties

4.@ConfigurationProperties+@EnableConfigurationProperties

@EnableConfigurationProperties一般使用在启动类上,让spring去扫描指定的Class类,value值是一个Class对象数组。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesImportSelector.class)
public @interface EnableConfigurationProperties {
	Class<?>[] value() default {};

}

使用

@SpringCloudApplication
@EnableAsync
@Slf4j
@EnableConfigurationProperties({XXXConfig.class})
public class FactoryApplication {
		。。。。
}
@ConfigurationProperties(prefix = "xxx.api.sign")
@Setter
@Getter
public class XXXConfig {
    /**
     *  签名key
     */
    private String key;
}

你可能感兴趣的:(spring,boot,spring,java,spring,cloud)