将@Conditional添加到Spring Boot中的现有spring注释中

问题描述 投票:0回答:2

我有一个使用现有弹簧注释(@EnableResourceServer)的应用程序。我希望仅当特定属性值不为false时才启用此特定注释。为此,我创建了一个元注释,并在其上应用了@ConditionalOnProperty

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ConditionalOnProperty(prefix = "custom.resource", name = "enabled", matchIfMissing = true)
@EnableResourceServer
public @interface EnableCustomResourceSecurity {
}

在我的应用程序中,我现在正在使用@EnableCustomResourceSecurity

@EnableCustomResourceSecurity
@SpringBootApplication
public class MyApplication {

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

}

并且如果该属性丢失或为true,则一切正常,但是当我将该属性更改为custom.resource.enabled=false时,出现以下异常:

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

[我尝试将此批注放置在其他两个位置,并注意到当该批注的条件表达式失败时,此后的任何批注也会停止处理。

实现我想做的正确方法是什么?

spring spring-boot spring-annotations
2个回答
0
投票

您的注释@EnableCustomResourceSecurity具有元注释@ConditionalOnProperty。尽管它可能[[似乎好像启用/禁用@EnableResourceServer注释,但它实际上整体上启用/禁用MyApplication bean。就像您会写:

@SpringBootApplication @ConditionalOnProperty(...) @EnableResourceServer public class MyApplication {
为避免这种情况,只需创建一个空的SomeConfiguration类,然后使用您的自定义注释对其进行注释:

@Configuration @EnableCustomResourceSecurity public class SomeConfiguration {}

而不是将其添加到您的MyApplication类中。

0
投票
我建议,您甚至不需要自定义注释,而只需Michiel提到的空配置。反过来,此配置也将导入@EnableResourceServer注释。

@Configuration @EnableResourceServer @ConditionalOnProperty(prefix = "custom.resource", name = "enabled", matchIfMissing = true) public class ResourceServerConfig { public ResourceServerConfig() { System.out.println("initializing ResourceServerConfig ..."); } }

如果要基于注释进行控制,可以在自定义注释中导入如下相同的配置:

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(ResourceServerConfig.class) public @interface EnableCustomResourceSecurity { }

© www.soinside.com 2019 - 2024. All rights reserved.