gpt4 book ai didi

java - 有没有办法将扩展 WebMvcConfigurerAdapter 和 WebSecurityConfigurerAdapter 的 @Configurations 合并到一个 @Configuration 中?

转载 作者:行者123 更新时间:2023-11-29 04:43:43 27 4
gpt4 key购买 nike

我想将两个配置合并为一个配置。这是它们目前的样子:

WebMvcConfigurerAdapter

@Configuration
@EnableWebMvc
@Import(...)
public class WebApplicationConfig extends WebMvcConfigurerAdapter {


@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
//...
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//...
}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
//...
}

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
//...
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//...
}

WebSecurityConfigurerAdapter

@EnableAsync
@EnableScheduling
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(
basePackages = {"..."})
@Import({
...
})
@PropertySources({
@PropertySource("..."),
@PropertySource(
ignoreResourceNotFound = true,
value = "...")
})
@EnableWebSecurity
@Configuration
public class AdminConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
//...
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//...
}

我查看了 Spring 类层次结构,发现这些类不会扩展以任何方式相关的类。是否存在替代它们的注释?这可以通过实现接口(interface)而不是扩展类来解决吗?

我想要合并这些的原因是因为我想要一个单一的配置,这样我在测试我的应用程序时就不必考虑使用哪个。

最佳答案

我不建议将它们放在同一个类(class)。出于同样的原因,您不建议将所有逻辑都塞进一个类中,这是不可取的。保持您的配置简明扼要。更重要的是,这有时真的会导致循环 bean 引用变得令人讨厌。

我建议通过组合来解决您的问题:

@Configuration
@Import({AdminConfig.class, WebApplicationConfig.class})
public class TheConfig {}

现在你可以直接引用TheConfig

或者,如果这只是关于测试,您可以将配置放在 meta annotation 上例如:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration(classes = {..})
public @interface TheTests { }

最后,如果你真的想使用一个类,你可以这样做:

@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 中的所有方法(只需实现您需要的那些)。更重要的是,它使您免受可能添加方法的界面中的更改的影响。

关于java - 有没有办法将扩展 WebMvcConfigurerAdapter 和 WebSecurityConfigurerAdapter 的 @Configurations 合并到一个 @Configuration 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com