The bean 'dataSource', defined in BeanDefinition defined in class path resource...












3















I'm using Spring Boot Security OAuth2 example by taking reference from https://www.devglan.com/spring-security/spring-boot-security-oauth2-example. In this example, I'm suing Spring Boot Parent version 2.1.1.RELEASE and spring-cloud-dependencies is Finchley.SR2.



Error:



2019-01-01 20:34:07.065  INFO 15028 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$79e639d7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _
( ( )___ | '_ | '_| | '_ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |___, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.1.RELEASE)

2019-01-01 20:34:08.724 INFO 15028 --- [ main] c.d.SpringBootSecurityOauth2Application : No active profile set, falling back to default profiles: default
2019-01-01 20:34:09.360 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-01-01 20:34:09.411 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 repository interfaces.
2019-01-01 20:34:09.815 WARN 15028 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.
2019-01-01 20:34:09.835 INFO 15028 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-01-01 20:34:09.837 ERROR 15028 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
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


application.yml



spring:
datasource:
# type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: root

jpa:
hibernate:
ddl-auto: update
show-sql: true

security:
oauth2:
resource:
filter-order: 3


User.java



@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column
private String username;

@Column(length = 60)
@JsonIgnore
private String password;

@Column
private long salary;

@Column
private int age;
}


SecurityConfig.java



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Resource(name = "userService")
private UserDetailsService userDetailsService;

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().anonymous().disable().authorizeRequests().antMatchers("/api-docs/**").permitAll();
}

@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}

@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}

@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);

FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}


ResourceServerConfig.java



@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

private static final String RESOURCE_ID = "resource_id";

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous().disable()
.authorizeRequests().antMatchers("/users/**").access("hasRole('ADMIN')")
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}


AuthorizationServerConfig.java



@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

static final String CLIEN_ID = "devglan-client";
static final String CLIENT_SECRET = "devglan-secret";
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

configurer.inMemory().withClient(CLIEN_ID).secret(CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
}
}









share|improve this question





























    3















    I'm using Spring Boot Security OAuth2 example by taking reference from https://www.devglan.com/spring-security/spring-boot-security-oauth2-example. In this example, I'm suing Spring Boot Parent version 2.1.1.RELEASE and spring-cloud-dependencies is Finchley.SR2.



    Error:



    2019-01-01 20:34:07.065  INFO 15028 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$79e639d7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

    . ____ _ __ _ _
    /\ / ___'_ __ _ _(_)_ __ __ _
    ( ( )___ | '_ | '_| | '_ / _` |
    \/ ___)| |_)| | | | | || (_| | ) ) ) )
    ' |____| .__|_| |_|_| |___, | / / / /
    =========|_|==============|___/=/_/_/_/
    :: Spring Boot :: (v2.1.1.RELEASE)

    2019-01-01 20:34:08.724 INFO 15028 --- [ main] c.d.SpringBootSecurityOauth2Application : No active profile set, falling back to default profiles: default
    2019-01-01 20:34:09.360 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
    2019-01-01 20:34:09.411 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 repository interfaces.
    2019-01-01 20:34:09.815 WARN 15028 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.
    2019-01-01 20:34:09.835 INFO 15028 --- [ main] ConditionEvaluationReportLoggingListener :

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-01-01 20:34:09.837 ERROR 15028 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

    ***************************
    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


    application.yml



    spring:
    datasource:
    # type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root

    jpa:
    hibernate:
    ddl-auto: update
    show-sql: true

    security:
    oauth2:
    resource:
    filter-order: 3


    User.java



    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column
    private String username;

    @Column(length = 60)
    @JsonIgnore
    private String password;

    @Column
    private long salary;

    @Column
    private int age;
    }


    SecurityConfig.java



    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().anonymous().disable().authorizeRequests().antMatchers("/api-docs/**").permitAll();
    }

    @Bean
    public TokenStore tokenStore() {
    return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder encoder() {
    return new BCryptPasswordEncoder();
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);

    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
    }
    }


    ResourceServerConfig.java



    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
    resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.anonymous().disable()
    .authorizeRequests().antMatchers("/users/**").access("hasRole('ADMIN')")
    .and()
    .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
    }


    AuthorizationServerConfig.java



    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    static final String CLIEN_ID = "devglan-client";
    static final String CLIENT_SECRET = "devglan-secret";
    static final String GRANT_TYPE_PASSWORD = "password";
    static final String AUTHORIZATION_CODE = "authorization_code";
    static final String REFRESH_TOKEN = "refresh_token";
    static final String IMPLICIT = "implicit";
    static final String SCOPE_READ = "read";
    static final String SCOPE_WRITE = "write";
    static final String TRUST = "trust";
    static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
    static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

    configurer.inMemory().withClient(CLIEN_ID).secret(CLIENT_SECRET)
    .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
    .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
    .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
    .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
    }
    }









    share|improve this question



























      3












      3








      3


      2






      I'm using Spring Boot Security OAuth2 example by taking reference from https://www.devglan.com/spring-security/spring-boot-security-oauth2-example. In this example, I'm suing Spring Boot Parent version 2.1.1.RELEASE and spring-cloud-dependencies is Finchley.SR2.



      Error:



      2019-01-01 20:34:07.065  INFO 15028 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$79e639d7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

      . ____ _ __ _ _
      /\ / ___'_ __ _ _(_)_ __ __ _
      ( ( )___ | '_ | '_| | '_ / _` |
      \/ ___)| |_)| | | | | || (_| | ) ) ) )
      ' |____| .__|_| |_|_| |___, | / / / /
      =========|_|==============|___/=/_/_/_/
      :: Spring Boot :: (v2.1.1.RELEASE)

      2019-01-01 20:34:08.724 INFO 15028 --- [ main] c.d.SpringBootSecurityOauth2Application : No active profile set, falling back to default profiles: default
      2019-01-01 20:34:09.360 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
      2019-01-01 20:34:09.411 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 repository interfaces.
      2019-01-01 20:34:09.815 WARN 15028 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.
      2019-01-01 20:34:09.835 INFO 15028 --- [ main] ConditionEvaluationReportLoggingListener :

      Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
      2019-01-01 20:34:09.837 ERROR 15028 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

      ***************************
      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


      application.yml



      spring:
      datasource:
      # type: com.zaxxer.hikari.HikariDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test
      username: root
      password: root

      jpa:
      hibernate:
      ddl-auto: update
      show-sql: true

      security:
      oauth2:
      resource:
      filter-order: 3


      User.java



      @Data
      @Builder
      @NoArgsConstructor
      @AllArgsConstructor
      @Entity
      public class User {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;

      @Column
      private String username;

      @Column(length = 60)
      @JsonIgnore
      private String password;

      @Column
      private long salary;

      @Column
      private int age;
      }


      SecurityConfig.java



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(prePostEnabled = true)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Resource(name = "userService")
      private UserDetailsService userDetailsService;

      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
      }

      @Autowired
      public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
      }

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http.csrf().disable().anonymous().disable().authorizeRequests().antMatchers("/api-docs/**").permitAll();
      }

      @Bean
      public TokenStore tokenStore() {
      return new InMemoryTokenStore();
      }

      @Bean
      public BCryptPasswordEncoder encoder() {
      return new BCryptPasswordEncoder();
      }

      @Bean
      public FilterRegistrationBean corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);
      config.addAllowedOrigin("*");
      config.addAllowedHeader("*");
      config.addAllowedMethod("*");
      source.registerCorsConfiguration("/**", config);

      FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
      bean.setOrder(0);
      return bean;
      }
      }


      ResourceServerConfig.java



      @Configuration
      @EnableResourceServer
      public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

      private static final String RESOURCE_ID = "resource_id";

      @Override
      public void configure(ResourceServerSecurityConfigurer resources) {
      resources.resourceId(RESOURCE_ID).stateless(false);
      }

      @Override
      public void configure(HttpSecurity http) throws Exception {
      http.anonymous().disable()
      .authorizeRequests().antMatchers("/users/**").access("hasRole('ADMIN')")
      .and()
      .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
      }
      }


      AuthorizationServerConfig.java



      @Configuration
      @EnableAuthorizationServer
      public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

      static final String CLIEN_ID = "devglan-client";
      static final String CLIENT_SECRET = "devglan-secret";
      static final String GRANT_TYPE_PASSWORD = "password";
      static final String AUTHORIZATION_CODE = "authorization_code";
      static final String REFRESH_TOKEN = "refresh_token";
      static final String IMPLICIT = "implicit";
      static final String SCOPE_READ = "read";
      static final String SCOPE_WRITE = "write";
      static final String TRUST = "trust";
      static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
      static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;

      @Autowired
      private TokenStore tokenStore;

      @Autowired
      private AuthenticationManager authenticationManager;

      @Override
      public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

      configurer.inMemory().withClient(CLIEN_ID).secret(CLIENT_SECRET)
      .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
      .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
      .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
      .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
      }

      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
      }
      }









      share|improve this question
















      I'm using Spring Boot Security OAuth2 example by taking reference from https://www.devglan.com/spring-security/spring-boot-security-oauth2-example. In this example, I'm suing Spring Boot Parent version 2.1.1.RELEASE and spring-cloud-dependencies is Finchley.SR2.



      Error:



      2019-01-01 20:34:07.065  INFO 15028 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$79e639d7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

      . ____ _ __ _ _
      /\ / ___'_ __ _ _(_)_ __ __ _
      ( ( )___ | '_ | '_| | '_ / _` |
      \/ ___)| |_)| | | | | || (_| | ) ) ) )
      ' |____| .__|_| |_|_| |___, | / / / /
      =========|_|==============|___/=/_/_/_/
      :: Spring Boot :: (v2.1.1.RELEASE)

      2019-01-01 20:34:08.724 INFO 15028 --- [ main] c.d.SpringBootSecurityOauth2Application : No active profile set, falling back to default profiles: default
      2019-01-01 20:34:09.360 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
      2019-01-01 20:34:09.411 INFO 15028 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 43ms. Found 1 repository interfaces.
      2019-01-01 20:34:09.815 WARN 15028 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.
      2019-01-01 20:34:09.835 INFO 15028 --- [ main] ConditionEvaluationReportLoggingListener :

      Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
      2019-01-01 20:34:09.837 ERROR 15028 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

      ***************************
      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


      application.yml



      spring:
      datasource:
      # type: com.zaxxer.hikari.HikariDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test
      username: root
      password: root

      jpa:
      hibernate:
      ddl-auto: update
      show-sql: true

      security:
      oauth2:
      resource:
      filter-order: 3


      User.java



      @Data
      @Builder
      @NoArgsConstructor
      @AllArgsConstructor
      @Entity
      public class User {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;

      @Column
      private String username;

      @Column(length = 60)
      @JsonIgnore
      private String password;

      @Column
      private long salary;

      @Column
      private int age;
      }


      SecurityConfig.java



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(prePostEnabled = true)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Resource(name = "userService")
      private UserDetailsService userDetailsService;

      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
      }

      @Autowired
      public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
      }

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http.csrf().disable().anonymous().disable().authorizeRequests().antMatchers("/api-docs/**").permitAll();
      }

      @Bean
      public TokenStore tokenStore() {
      return new InMemoryTokenStore();
      }

      @Bean
      public BCryptPasswordEncoder encoder() {
      return new BCryptPasswordEncoder();
      }

      @Bean
      public FilterRegistrationBean corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);
      config.addAllowedOrigin("*");
      config.addAllowedHeader("*");
      config.addAllowedMethod("*");
      source.registerCorsConfiguration("/**", config);

      FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
      bean.setOrder(0);
      return bean;
      }
      }


      ResourceServerConfig.java



      @Configuration
      @EnableResourceServer
      public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

      private static final String RESOURCE_ID = "resource_id";

      @Override
      public void configure(ResourceServerSecurityConfigurer resources) {
      resources.resourceId(RESOURCE_ID).stateless(false);
      }

      @Override
      public void configure(HttpSecurity http) throws Exception {
      http.anonymous().disable()
      .authorizeRequests().antMatchers("/users/**").access("hasRole('ADMIN')")
      .and()
      .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
      }
      }


      AuthorizationServerConfig.java



      @Configuration
      @EnableAuthorizationServer
      public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

      static final String CLIEN_ID = "devglan-client";
      static final String CLIENT_SECRET = "devglan-secret";
      static final String GRANT_TYPE_PASSWORD = "password";
      static final String AUTHORIZATION_CODE = "authorization_code";
      static final String REFRESH_TOKEN = "refresh_token";
      static final String IMPLICIT = "implicit";
      static final String SCOPE_READ = "read";
      static final String SCOPE_WRITE = "write";
      static final String TRUST = "trust";
      static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
      static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;

      @Autowired
      private TokenStore tokenStore;

      @Autowired
      private AuthenticationManager authenticationManager;

      @Override
      public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

      configurer.inMemory().withClient(CLIEN_ID).secret(CLIENT_SECRET)
      .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
      .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
      .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
      .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
      }

      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
      }
      }






      spring spring-security spring-security-oauth2






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 15:05







      PAA

















      asked Jan 1 at 14:25









      PAAPAA

      2,72922238




      2,72922238
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Spring Cloud Finchley release train is not compatible to Spring Boot 2.1.x out of the box. You need to upgrade from Finchley.SR2 to Greenwich.RELEASE.



          See the section “Release Trains” on the Spring Cloud homepage:



          Spring Cloud compatibility matrix






          share|improve this answer































            1














            Please see and add the last 2 lines inside your application.yml:



            spring:
            datasource:
            # type: com.zaxxer.hikari.HikariDataSource
            driver-class-name: com.mysql.jdbc.Driver
            url: jdbc:mysql://localhost:3306/test
            username: root
            password: root

            jpa:
            hibernate:
            ddl-auto: update
            show-sql: true
            main:
            allow-bean-definition-overriding: true





            share|improve this answer
























            • still its not working

              – PAA
              Jan 7 at 4:40






            • 1





              Try changing your spring cloud dependency to Greenwich.M3

              – Zaccus
              Jan 7 at 6:26











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996250%2fthe-bean-datasource-defined-in-beandefinition-defined-in-class-path-resource%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Spring Cloud Finchley release train is not compatible to Spring Boot 2.1.x out of the box. You need to upgrade from Finchley.SR2 to Greenwich.RELEASE.



            See the section “Release Trains” on the Spring Cloud homepage:



            Spring Cloud compatibility matrix






            share|improve this answer




























              1














              Spring Cloud Finchley release train is not compatible to Spring Boot 2.1.x out of the box. You need to upgrade from Finchley.SR2 to Greenwich.RELEASE.



              See the section “Release Trains” on the Spring Cloud homepage:



              Spring Cloud compatibility matrix






              share|improve this answer


























                1












                1








                1







                Spring Cloud Finchley release train is not compatible to Spring Boot 2.1.x out of the box. You need to upgrade from Finchley.SR2 to Greenwich.RELEASE.



                See the section “Release Trains” on the Spring Cloud homepage:



                Spring Cloud compatibility matrix






                share|improve this answer













                Spring Cloud Finchley release train is not compatible to Spring Boot 2.1.x out of the box. You need to upgrade from Finchley.SR2 to Greenwich.RELEASE.



                See the section “Release Trains” on the Spring Cloud homepage:



                Spring Cloud compatibility matrix







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 13 at 13:38









                pvorbpvorb

                4,08763262




                4,08763262

























                    1














                    Please see and add the last 2 lines inside your application.yml:



                    spring:
                    datasource:
                    # type: com.zaxxer.hikari.HikariDataSource
                    driver-class-name: com.mysql.jdbc.Driver
                    url: jdbc:mysql://localhost:3306/test
                    username: root
                    password: root

                    jpa:
                    hibernate:
                    ddl-auto: update
                    show-sql: true
                    main:
                    allow-bean-definition-overriding: true





                    share|improve this answer
























                    • still its not working

                      – PAA
                      Jan 7 at 4:40






                    • 1





                      Try changing your spring cloud dependency to Greenwich.M3

                      – Zaccus
                      Jan 7 at 6:26
















                    1














                    Please see and add the last 2 lines inside your application.yml:



                    spring:
                    datasource:
                    # type: com.zaxxer.hikari.HikariDataSource
                    driver-class-name: com.mysql.jdbc.Driver
                    url: jdbc:mysql://localhost:3306/test
                    username: root
                    password: root

                    jpa:
                    hibernate:
                    ddl-auto: update
                    show-sql: true
                    main:
                    allow-bean-definition-overriding: true





                    share|improve this answer
























                    • still its not working

                      – PAA
                      Jan 7 at 4:40






                    • 1





                      Try changing your spring cloud dependency to Greenwich.M3

                      – Zaccus
                      Jan 7 at 6:26














                    1












                    1








                    1







                    Please see and add the last 2 lines inside your application.yml:



                    spring:
                    datasource:
                    # type: com.zaxxer.hikari.HikariDataSource
                    driver-class-name: com.mysql.jdbc.Driver
                    url: jdbc:mysql://localhost:3306/test
                    username: root
                    password: root

                    jpa:
                    hibernate:
                    ddl-auto: update
                    show-sql: true
                    main:
                    allow-bean-definition-overriding: true





                    share|improve this answer













                    Please see and add the last 2 lines inside your application.yml:



                    spring:
                    datasource:
                    # type: com.zaxxer.hikari.HikariDataSource
                    driver-class-name: com.mysql.jdbc.Driver
                    url: jdbc:mysql://localhost:3306/test
                    username: root
                    password: root

                    jpa:
                    hibernate:
                    ddl-auto: update
                    show-sql: true
                    main:
                    allow-bean-definition-overriding: true






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 7 at 1:44









                    ZaccusZaccus

                    187




                    187













                    • still its not working

                      – PAA
                      Jan 7 at 4:40






                    • 1





                      Try changing your spring cloud dependency to Greenwich.M3

                      – Zaccus
                      Jan 7 at 6:26



















                    • still its not working

                      – PAA
                      Jan 7 at 4:40






                    • 1





                      Try changing your spring cloud dependency to Greenwich.M3

                      – Zaccus
                      Jan 7 at 6:26

















                    still its not working

                    – PAA
                    Jan 7 at 4:40





                    still its not working

                    – PAA
                    Jan 7 at 4:40




                    1




                    1





                    Try changing your spring cloud dependency to Greenwich.M3

                    – Zaccus
                    Jan 7 at 6:26





                    Try changing your spring cloud dependency to Greenwich.M3

                    – Zaccus
                    Jan 7 at 6:26


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996250%2fthe-bean-datasource-defined-in-beandefinition-defined-in-class-path-resource%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    How to fix TextFormField cause rebuild widget in Flutter