H5W3
当前位置:H5W3 > java > 正文

【Java】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,请问各位大神是哪里写的不对呢?谢谢

回答

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

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

本文地址:H5W3 » 【Java】spring boot 读取.yml失败

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址