Spring игнорирует @Primary аннотации - PullRequest
0 голосов
/ 19 марта 2020

У меня есть код, который пытается переопределить bean-компонент ( RedisIndexedSessionRepository ), определенный во внешней зависимости (spring-session-data-redis: 2.2.0).

Вот полный источник класса с определением бина . Соответствующая часть ниже:

@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;
    }

    // ...
}

Когда я пытаюсь запустить приложение, в консоль записывается ошибка:

Параметру 0 конструктора в org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration $ SessionCleanupConfiguration требуется один компонент, но найдено 2: // перечисляет компоненты из обоих классов здесь Действие:

Попробуйте пометить один из компонентов как @Primary, обновить получателя для приема нескольких компонентов или использовать @Qualifier для определения компонента, который следует использовать

Любые идеи почему @ Primary здесь не учитывается?

1 Ответ

1 голос
/ 19 марта 2020

Просто добавьте одно свойство в вашу конфигурацию:

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;
    }

    // ...
}
...