美文网首页
基于配置和环境灵活加载 Beans

基于配置和环境灵活加载 Beans

作者: 清十郎sama | 来源:发表于2019-12-23 17:33 被阅读0次

Spring Boot 开发过程中我们经常会写一些 Configuration Class 来定义 Beans。只要你的代码没问题,这些 Configuration Class 默认都会生效,类下的 Beans 都会被加载。但在实际情况中,我们在不同的环境,或者不同一些场景下我们可能需要禁用这些 Configuration Class。而这篇文章就给大家总结了一些灵活控制 Configuration Class 是否生效的方法。

这些方法并不局限于 @Configuration,参考:how-to-conditionally-enable-or-disable-scheduled-jobs-in-spring

方法一:通过 @Profile 注解

@Profile 注解可以让你声明一个 Configuration Class 仅在相应 Profiles Active 时才会生效。

package xxx;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
 
@Configuration
@Profile({"dev","test"})
public class XXXConfiguration {
 
    @Bean
    public XXX A() {
        return XXX;
    }
 
    @Bean
    public XXX B() {
        return XXX;
    }
 
}

上面这段代码就是说,仅当 profile “dev” 或者 “test” 是 active 时(即 spring.profiles.active=dev or spring.profiles.active=test or spring.profiles.active=dev,test 时),XXXConfiguration Class 才会被加载。

方法二:通过 @ConditionalOnProperty 注解

通过 Profiles 来界定一个 Configuration Class 是否应该被加载是我们最常碰到的需求,换句话说 @Profile 可以解决大部分问题。但有时候,我们也希望通过一个专门的配置(在 application.properties/application.yaml 里面配置一下)这种方式来控制是否加载一个对应的 Configuration Class。这时,我们可以用到 @ConditionalOnProperty。

package xxx;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
 
@Configuration
@ConditionalOnProperty(name="xxx.enabled", havingValue = "true")
public class XXXConfiguration {
 
    @Bean
    public XXX A() {
        return XXX;
    }
 
    @Bean
    public XXX B() {
        return XXX;
    }
 
}

此时,仅当配置项“xxx.enabled”的值为“true时,XXXConfiguration Class 才会被加载。如果“xxx.enabled”为空则 XXXConfiguration Class 也不会被加载。

相关文章

  • 基于配置和环境灵活加载 Beans

    Spring Boot 开发过程中我们经常会写一些 Configuration Class 来定义 Beans。只...

  • Vapor文档学习四 :Config

    应用的配置通常都是基于他们部署的环境。Vapor为用户自定义提供了灵活的配置选择。 QuickStart Vapo...

  • Flask使用工程模式创建Flask app

    使用工厂模式创建flask app,并结合适用配置对象与环境变量加载配置信息 使用配置对象加载默认配置 使用环境变...

  • logback.xml读取spring的属性

    使用springProfile和springProperty实现多环境的灵活配置,不用再使用多个不同的配置文件lo...

  • Spring Boot启动-构造容器环境

    容器的运行环境包含了应用配置和环境相关信息,后面所有关于配置和环境的操作都基于此类。构建容器环境实现代码如下: 从...

  • pyera开发环境配置

    pyera引擎的开发环境非常灵活,可以根据不同的功能需求等级进行选择。分为两种配置,和两个进阶功能: 简易配置环境...

  • Spring Profile

    Profile作用 用来解决不同环境下加载不同类、配置的一种方式。例如在项目环境和线上环境数据库配置不同,可用通过...

  • uos linux启动流程

    设备加电->加载bios->读取主引导记录->启动加载器->(加载内核->初始化环境->配置系统环境->启动内核模...

  • webstorm nodejs 项目启动加载对应环境配置

    项目中有3个环境配置,我想本地启动的时候默认加载qa.js 环境配置。

  • Thinkjs怎么操作数据库

    配置 ThinkJS 提供了灵活的配置,可以在不同的模块和不同的项目环境下使用不同的配置,且这些配置在服务启动时就...

网友评论

      本文标题:基于配置和环境灵活加载 Beans

      本文链接:https://www.haomeiwen.com/subject/npqtoctx.html