Проблема при изменении версии Spring Boot с 2.0.3.RELEASE на 2.1.0.BUILD-SNAPSHOT
У меня есть рабочий код, который перестает работать, когда я меняю версию Spring Boot с 2.0.3.RELEASE
в 2.1.0.BUILD-SNAPSHOT
,
Иногда ошибка:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'dataSource', defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
или же...
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-07-16 14:38:18.509 ERROR 604 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'scopedTarget.oauth2ClientContext', defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration$ClientContextConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/security/oauth2/config/annotation/web/configuration/OAuth2ClientConfiguration$OAuth2ClientContextConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
В обоих случаях это связано с дублированием бобов или чем-то еще.
Мои зависимости POM:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.BUILD-SNAPSHOT</spring-cloud.version>
<maven.test.skip>true</maven.test.skip>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
и конфиг:
server:
error:
include-stacktrace: always
whitelabel:
enabled: false
servlet:
session:
cookie:
name: HYDRASSESSION
port: 36205
management:
endpoints:
web:
exposure:
include: "*"
security:
basic:
enabled: false
oauth2:
client:
clientId: atlas
clientSecret: secret
accessTokenUri: http://myserverip:36202/oauth/token
userAuthorizationUri: http://myserverip:36202/oauth/authorize
resource:
userInfoUri: http://myserverip:36202/user/me
spring:
jpa:
properties:
hibernate:
temp:
use_jdbc_metadata_defaults: false
hibernate:
ddl-auto: validate
application:
name: atlas
datasource:
password: admin
username: postgres
url: jdbc:postgresql://myserverip:36211/atlas?ApplicationName=Atlas
guardiao:
logout:
path: http://myserverip:36202/exit
Работает нормально при использовании 2.0.3.RELEASE
но я получаю сообщение об ошибке при попытке войти myserver:36202/oauth/authorize?client_id=
: браузером жалуется ERR_TOO_MANY_REDIRECTS
но у меня нет ошибок в консоли. Во всяком случае... мой вопрос: как я могу обновить SpringBoot до 2.1.0.BUILD-SNAPSHOT?
3 ответа
Таким образом, как отчеты об исключениях, есть два бина одного типа. Исторически весна переопределяла один боб другим. Это долго раздражало, так как было трудно найти ошибки, когда второй бин совершенно другого типа, но с таким же идентификатором бина, заставил бы ваш первый бин исчезнуть.
Spring Boot 2 теперь по умолчанию отключает переопределение bean-компонентов. Вы можете снова включить его, установив следующее свойство в вашем application.yml:
spring.main.allow-bean-definition-overriding: true
Это повторно включает предыдущее поведение. Это не устраняет основную причину переопределения bean-компонентов, а также означает, что вы не получите выгоду от ошибок переопределения bean-компонентов. Мы надеемся, что обновление базовых библиотек со временем очистит это.
Как отмечено в других комментариях, обновление spring-security-oauth2-autoconfigure
зависимость от org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.0.RELEASE
может решить это за вас.
Пожалуйста, не меняйте версию Spring Boot, когда ваш проект находится между разработками. Попробуйте добавить последнюю версию при запуске проекта. Как только разработка началась, ничего не меняйте в версии. Я столкнулся с той же проблемой и потратил 4-5 часов и снова вернулся к предыдущей версии, все работает отлично.
Этот ответ может быть полезен для тех, кто настроил новый проект и добавил
spring.main.allow-bean-definition-overriding: true
свойство в файле не устраняет проблему:
Проверьте папку, в которой находится ваш
application.properties
файл присутствует - он должен быть доступен непосредственно в каталоге:
src/main/resources/
и нигде больше.