在 Springboot 中有条件地应用 @EnableJms

Jim*_*Jim 1 java spring spring-jms spring-boot

鉴于以下 spring/boot 应用程序。

@SpringBootApplication
@Configuration
@ComponentScan
@EnableGlobalMethodSecurity(
        prePostEnabled = true,
        securedEnabled = false,
        jsr250Enabled = false)

@EnableJms // we would like to control this from an application property on/off
public class PayZilchCustomerServiceApplication {
    static {
        SSLUtilities.trustAllHostnames();
        SSLUtilities.trustAllHttpsCertificates();
    }
    public static void main(String[] args) {
        SpringApplication.run(PayZilchCustomerServiceApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们发现对于一些我们想要@EnableJms关闭的本地调试场景。我们注释掉这行代码。我们偶尔会创建带有注释行的 PR。PR 被代码审查捕获。

总有一天会过去的。我们如何@EnableJms从应用程序属性文件进行控制,最好是默认情况下它是打开的,但可以通过application-local.properties条目关闭。

Far*_*raz 5

创建一个新类并使用以下 3 个注释对其进行标记:

@Configuration
@EnableJms
@ConditionalOnProperty(name = "turnonjms", havingValue = "true")
public class MyEnableJmsCustomConfig {
   //you can keep it empty. Just make sure this class
   //is present in the same folder where main class is
}
Run Code Online (Sandbox Code Playgroud)

turnonjms将从外部来源(如运行时参数--turnonjms=true-Dturnonjms. 如果它存在,则只有那时@EnableJms才会处于活动状态。否则它会关闭。

或者,如果您愿意,您可以始终启用 JMS 并仅在存在某些外部属性时将其关闭:

@ConditionalOnProperty(name = "turoffjms", havingValue = "false")
Run Code Online (Sandbox Code Playgroud)

如果您turnoffjms从外部来源传递属性,那么您将始终启用 JMS。如果通过--turnoffjms=true,JMS 将被禁用。

附带说明一下,当您使用 时@SpringBootApplication,它已经包含@configuration@ComponentScan注释。@ComponentScan如果您要扫描当前包之外的文件夹,您会想要使用。EnableGlobalMethodSecurity(...)也有 Embedded @Configuration,因此从主类中删除这两个注释是安全的。

编辑:

由于您已经在使用 application-local.properties,请插入此条目以将其关闭:

turnoffjms: true#true如果不起作用,请用双引号引起来