Is there a way to merge @Configurations that extend WebMvcConfigurerAdapter and WebSecurityConfigurerAdapter into one @Configuration?
我想将两种配置合并为一种配置。以下是它们目前的外观:
WebMvcConfigurerAdapter
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@Configuration
@EnableWebMvc @Import(…) public class WebApplicationConfig extends WebMvcConfigurerAdapter {
@Override @Override @Override @Override @Override |
WebSecurityConfigurerAdapter
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
@EnableAsync
@EnableScheduling @EnableTransactionManagement @EnableAspectJAutoProxy(proxyTargetClass = true) @ComponentScan( basePackages = {“…”}) @Import({ … }) @PropertySources({ @PropertySource(“…”), @PropertySource( ignoreResourceNotFound = true, value =“…”) }) @EnableWebSecurity @Configuration public class AdminConfig extends WebSecurityConfigurerAdapter { @Override @Override |
我已经查看了 Spring 类层次结构,发现它们不会以任何方式扩展相关的类。是否存在可以替换它们的注释?这可以通过实现接口而不是扩展类来解决吗?
我想要合并这些的原因是因为我想要一个单一的配置,这样我在测试我的应用程序时就不必考虑使用哪个配置。
我不建议将它们放在同一个班级。出于同样的原因,您不建议将所有逻辑都塞进一个类中,这是不可取的。保持配置简洁明了。更重要的是,这有时真的会得到讨厌的 w/圆形 bean 引用。
我建议你做作文来解决你的问题:
1
2 3 |
@Configuration
@Import({AdminConfig.class, WebApplicationConfig.class}) public class TheConfig {} |
现在你可以参考 TheConfig.
或者,如果这只是关于测试,您可以将配置放在元注释上 例如:
1
2 3 4 |
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @ContextConfiguration(classes = {..}) public @interface TheTests { } |
最后,如果你真的想使用单个类,你可以这样做:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@EnableWebMvc
@Import(…) @EnableAsync @EnableScheduling @EnableTransactionManagement @EnableAspectJAutoProxy(proxyTargetClass = true) @ComponentScan( basePackages = {“…”}) @Import({ … }) @PropertySources({ @PropertySource(“…”), @PropertySource( ignoreResourceNotFound = true, value =“…”) }) @EnableWebSecurity @Configuration public class TheConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer { … } |
另外一个问题是提供了 WebMvcConfigurerAdapter,所以你不需要实现 API 中的所有方法(只有你需要的那些)。更重要的是它可以保护您免受界面内可能添加方法的更改。
最简单和最惯用的方法是让每个配置器成为顶级 @Configuration 类上的静态嵌套类:
1
2 3 4 5 6 7 8 9 10 |
@Configuration
public class TestConfig { @Configuration @EnableWebSecurity public class Security extends WebSecurityConfigurerAdapter { … } … |
导入顶层类,Spring也会导入嵌套配置。
来源:https://www.codenong.com/38152752/