whs_321
2018-07-23 09:40
采纳率: 11.1%
浏览 4.4k

spring boot 读取.yml失败

1、application.yml

spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://192.168.2.201:3306/pmsd?useUnicode=true&characterEncoding=utf8&ssl=false
    username: app_pmsd
    password: 635151_Itp
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      initial-size: 1
      minIdle: 5
      maxActive: 20
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000

2、DataSourceProperties.java

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
    private String url;
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

3、MybatisConfigurer.java

@Configuration
public class MybatisConfigurer {
    @Autowired
    private DataSourceProperties dataSourceProperties;
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        //druidDataSource.setUsername(dataSourceProperties.getUserName());
        //druidDataSource.setPassword(dataSourceProperties.getPassWord());
        //druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        return druidDataSource;
    }
   }

4、pom.xml有引用

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
  </dependency>
    ```

代码如上,我在获取dataSourceProperties得到的是null,请问各位大神是哪里写的不对呢?谢谢
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • qq_38535182 2018-07-23 09:43

    DataSourceProperties 里加入代码

     public DataSource config(DruidDataSource dataSource){
            dataSource.setUrl(url);
            return dataSource;
     }
    

    MybatisConfigurer里修改为

         @Bean
        public DruidDataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            druidProperties.config(dataSource);
            return dataSource;
        }
    
    打赏 评论
  • java_66666 2018-07-23 09:45

    在MybatisConfigurer类中还有另外一个方法MapperScannerConfigurer造成的,因为spring会首先执行MapperScannerConfigurer方法,在执行的时候还没有创建sqlsessionFactory,所以就会造成空指针异常

    打赏 评论
  • u014795242 2018-07-26 03:33

    首先
    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
    this.url = url;
    }
    是不是得在配置类中 添加@Value获取url的值啊!
    其次 规范一下@Configuration和@Component注解的用法;建议MybatisConfigurer创建bean使用@Component,而配置上面DataSourceProperties 使用@Configuration;我感觉出现为null的问题是因为先后创建bean的问题导致的。

    打赏 评论

相关推荐 更多相似问题