我有一个使用现有弹簧注释(@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.
[我尝试将此批注放置在其他两个位置,并注意到当该批注的条件表达式失败时,此后的任何批注也会停止处理。
实现我想做的正确方法是什么?
您的注释@EnableCustomResourceSecurity
具有元注释@ConditionalOnProperty
。尽管它可能[[似乎好像启用/禁用@EnableResourceServer
注释,但它实际上整体上启用/禁用MyApplication
bean。就像您会写:
@SpringBootApplication
@ConditionalOnProperty(...)
@EnableResourceServer
public class MyApplication {
为避免这种情况,只需创建一个空的SomeConfiguration
类,然后使用您的自定义注释对其进行注释:
@Configuration @EnableCustomResourceSecurity public class SomeConfiguration {}
而不是将其添加到您的MyApplication
类中。
@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 { }