gpt4 book ai didi

java - Spring忽略@Primary注解

转载 作者:行者123 更新时间:2023-12-02 08:51:14 26 4
gpt4 key购买 nike

我有一个代码尝试覆盖外部依赖项 (spring-session-data-redis:2.2.0) 中定义的 bean (RedisIndexedSessionRepository)。

Here's a full source of a class with bean definition 。相关部分如下:

@Configuration(proxyBeanMethods = false)
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration
implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware {
// ...

@Bean
public RedisIndexedSessionRepository sessionRepository() {
// constructs and returns sessionRepository
}

// ...

@EnableScheduling
@Configuration(proxyBeanMethods = false)
class SessionCleanupConfiguration implements SchedulingConfigurer {

private final RedisIndexedSessionRepository sessionRepository;

SessionCleanupConfiguration(RedisIndexedSessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}

// ...
}
}

下面是尝试覆盖 bean 的代码:

@EnableRedisHttpSession
@Configuration
public class CustomRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration {
// ...

@Bean
@Primary
public RedisIndexedSessionRepository customSessionRepository() {
RedisIndexedSessionRepository sessionRepository = super.sessionRepository();
// custom config code
return safeRepository;
}

// ...
}

当我尝试启动应用程序时,控制台会记录一个错误:

Parameter 0 of constructor in org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration$SessionCleanupConfiguration required a single bean, but 2 were found: // lists beans from both classes here Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

有什么想法为什么这里不考虑@Primary吗?

最佳答案

只需向您的配置添加一个属性即可:

spring.main.allow-bean-definition-overriding=true

编辑

或者尝试类似的事情:

@EnableRedisHttpSession
@Configuration
public class CustomRedisHttpSessionConfiguration extends
RedisHttpSessionConfiguration implements BeanPostProcessor {
// ...

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass() == RedisIndexedSessionRepository.class) {
RedisIndexedSessionRepository sessionRepository = (RedisIndexedSessionRepository) bean;
// custom config code
}
return bean;
}

// ...
}

关于java - Spring忽略@Primary注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60753734/

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