1

我有一些代码可以在版本 2 之前的 spring boot 上正常工作,但我发现很难将其转换为 spring boot 2。

有人可以帮忙吗?

.yml 文件:

spring:
   datasource:
      type: org.apache.tomcat.jdbc.pool.DataSource
      tomcat:
         initial-size: 10
         max-active: 20
         max-idle: 10
         max-wait: 10000

旧代码:

       DataSource dataSource = builder.build();

        Map<String, Object> properties = null;

            try {
                RelaxedPropertyResolver relaxedProperty = new RelaxedPropertyResolver(environment);
                properties = relaxedProperty
                    .getSubProperties("spring.datasource.tomcat.");
            } catch (Exception e) {
                  // No need to log an error
            }
            MutablePropertyValues mutableProperties = new MutablePropertyValues(properties);            
            if(properties == null || properties.isEmpty()) {

                return dataSource;
            }
            new RelaxedDataBinder(dataSource).bind(mutableProperties);

            return dataSource;

版本 2 的新代码:

   DataSourceBuilder<?> dataSourceBuilder =  
   DataSourceBuilder.create(this.getClass().getClassLoader());
    javax.sql.DataSource dataSource = dataSourceBuilder.build();

        Map<String, Object> properties = null;

            try {

                properties = Binder.get(environment)
                        .bind("spring.datasource.tomcat", Bindable.mapOf(String.class, Object.class)).orElseGet(Collections::emptyMap);

            } catch (Exception e) {
                  // No need to log an error
            }
            if(properties == null || properties.isEmpty()) {
                return dataSource;
            }
            return Binder.get(environment)
                     .bind("spring.datasource.tomcat", DataSource.class).get();

将数据绑定到 DataSource.class 时出现以下错误。当我将数据源替换为 poolProperties 类时,它将能够绑定但我无法绑定此数据源。
Binder.get(环境) .bind("spring.datasource.tomcat", PoolProperties.class).get();:

错误:

   java.util.NoSuchElementException: No value bound
at org.springframework.boot.context.properties.bind.BindResult.get(BindResult.java:56)
4

0 回答 0