SpringBoot2.0版本对于配置文件的读取

@ConfigurationProperties 2.0已不支持,虽然编译通过,但是IDEA会有个错误提示
提示为Spring Boot Configuration Annotation Processor not found in classpath
我为了解决这个提示 查了好多资料 但是都是SpringBoot1.5版本或更低的版本用spring-boot-configuration-processor 来解决,官方文档上也没给出demo,最后忘记在哪个网站上找到
通过ApplicationContext上下文获取Environment,再通过Binder 获取配置文件的方法,再查询Environment 的获取方式,选择了自动注入方式。

而即使你引入了processor jar包 并下载下来了,但pom.xml还是会报一个错误

Failed to read artifact descriptor for org.springframework.boot:spring-boot-configuration-processor:jar:2.0.4.RELEASE less... (Ctrl+F1) 
Inspection info: Inspects a Maven model for resolution problems.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
package com.pbh.springbootdemo;

//import org.mybatis.spring.annotation.MapperScan;
//import com.pbh.springbootdemo.properties.datasource.ReadDataSourceProperties;
import com.pbh.springbootdemo.properties.datasource.ReadDataSourceProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.boot.context.properties.bind.Bindable;
//import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
//@MapperScan("com.pbh.springbootdemo.mapper")
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringbootdemoApplication.class, args);
        Binder binder = Binder.get(context.getEnvironment()); //绑定简单配置
        ReadDataSourceProperties foo = binder.bind("spring.read", Bindable.of(ReadDataSourceProperties.class)).get();
        //ReadDataSourceProperties readDataSourceProperties = binder.bind("spring.read",ReadDataSourceProperties.class).get();
        System.out.println(foo.getUrl());
    }
}

@PropertySource 用于标识自定义配置文件位置 如果是application.yml(application.properties) 可以不用,因为SpringBoot 会自动扫描application.yml(application.properties)
@Component 标识此class为组件 用于自动注入 但2.0不需要自动注入 所以不用
属性名称的对应 driverClassName 对应 yml(xml)里的 driver-class-name
SpringBoot建议以小写字母+-+ 小写字母 的方式在xml或yml中命名属性

配置文件class

package com.pbh.springbootdemo.properties.datasource;

//import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
//import org.springframework.stereotype.Component;

/**
 * @ClassName MasterDataSourceProperties
 * @Descrition 主库数据库配置
 * @Author pbh
 * @Date 2018/9/3 11:17
 * @Version 1.0
 **/
//@Component
@PropertySource("classpath:application.yml")
//@ConfigurationProperties(prefix = "spring.master") 
public class MasterDataSourceProperties {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    private String type;

    private int maxActive;

    private int initialSize;

    private int minIdle;

    private long maxWait;

    private int timeBetweenEvictionRunsMillis;

    private long minEvictableIdleTimeMillis;

    private boolean testWhileIdle;

    private boolean testOnBorrow;

    private boolean testOnReturn;

    private boolean poolPreparedStatements;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public long getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(long maxWait) {
        this.maxWait = maxWait;
    }

    public int getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public long getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public boolean isTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public boolean isPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }
}

建议使用yml方式配置属性文件,IDEA 对于yml文件有自动提示很友好(自定义的除外),看起来很清爽,以后会慢慢代替xml成为一种趋势
application.yml
一定要注意各个层次 否则很容易程序报错

server:
  port: 8080

spring:
  application:
    name: springbootdemo
  aop: proxy-target-class=false
  #datasource:
    #name: test
    #type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    #druid:
      #监控统计拦截的filters
      #filters: stat
      #driver-class-name: com.mysql.jdbc.Driver
      #基本属性
      #url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
      #username: root
      #password: root
      #配置初始化大小/最小/最大
      #initial-size: 1
      #min-idle: 1
      #max-active: 20
      #获取连接等待超时时间
      #max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      #time-between-eviction-runs-millis: 60000
      #一个连接在池中最小生存的时间
      #min-evictable-idle-time-millis: 300000
      #validation-query: SELECT 'x'
      #test-while-idle: true
      #test-on-borrow: false
      #test-on-return: false
      #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      #pool-prepared-statements: false
      #max-pool-prepared-statement-per-connection-size: 20
  #读写分离配置
  master: #主库 拥有读写权限
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;emptyStringsConvertToZero=true
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    max-active: 20
    initial-size: 1
    min-idle: 3
    max-wait: 600
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true

  read:  #从库 拥有读权限
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;emptyStringsConvertToZero=true
    username: read
    password: root123
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    max-active: 20
    initial-size: 1
    min-idle: 3
    max-wait: 600
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true
  swagger:
    enabled: true #是否开启
    title: swagger demo #标题
    description: spring boot demo #描述
    version: 1.0.0  #版本
    base-package: com.pbh.springbootdemo.controller #swagger扫描的基础包,默认:全扫描(分组情况下此处可不配置)
    #定义的api的前缀,必须已/开头,测试用例的主机则为:host+bashPath
    #basePath: /api
    contact: #维护者信息
      name: pbh,xjl #名字
      #全局参数,比如Token之类的验证信息可以全局话配置
      #global-operation-parameters:
        #description: 'Token信息,必填项'
        #modelRef: 'string'
        #name: 'Authorization'
        #parameter-type: 'header'
        #required: true
      #groups:
        #basic-group:
          #base-package: com.battcn.controller.basic
        #system-group:
          #base-package: com.battcn.controller.system
    security:
      username: admin
      password: admin
      filter-plugin: false #开启登录
    validator-plugin: false #是否开启Bean 验证插件 默认false

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
#mybatis:
  #mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  #type-aliases-package: com.pbh.model  # 注意:对应实体类的路径

#分页
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  returnPageInfo: check
#配置sql日志
logging:
  level:
    com.pbh.springbootdemo.mapper: debug # 改成你的mapper文件所在包路径(debug级别只比trace低)

读取配置文件class
这里使用自动注入Environment
然后使用SpringBoot 推荐的Binder读取配置文件

 Binder binder = Binder.get(environment); //绑定简单配置
 this.readDataSourceProperties = binder.bind("spring.read", Bindable.of(ReadDataSourceProperties.class)).get();
 this.masterDataSourceProperties = binder.bind("spring.master",Bindable.of(MasterDataSourceProperties.class)).get();
package com.pbh.springbootdemo.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.pbh.springbootdemo.properties.datasource.MasterDataSourceProperties;
import com.pbh.springbootdemo.properties.datasource.ReadDataSourceProperties;
//import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.EnvironmentAware;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
//import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
//import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DataBaseConfiguration
 * @Descrition Druid的DataResource配置类
 * @Author PanBaihui
 * @Date 2018/9/3 10:46
 * @Version 1.0
 **/
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration {

    @Autowired
    private Environment environment;

    private MasterDataSourceProperties masterDataSourceProperties;

    private ReadDataSourceProperties readDataSourceProperties;

    public DataBaseConfiguration(){
        System.out.println("-----------  DataBaseConfigurationStart  -----------");
    }

   public void setProperties() {
        Binder binder = Binder.get(environment); //绑定简单配置
        this.readDataSourceProperties = binder.bind("spring.read", Bindable.of(ReadDataSourceProperties.class)).get();
        this.masterDataSourceProperties = binder.bind("spring.master",Bindable.of(MasterDataSourceProperties.class)).get();
    }

    public DataSource master() {
        System.out.println("注入Master数据源!!!");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(masterDataSourceProperties.getUrl());
        datasource.setDriverClassName(masterDataSourceProperties.getDriverClassName());
        datasource.setUsername(masterDataSourceProperties.getUsername());
        datasource.setPassword(masterDataSourceProperties.getPassword());
        datasource.setInitialSize(masterDataSourceProperties.getInitialSize());
        datasource.setMinIdle(masterDataSourceProperties.getMinIdle());
        datasource.setMaxWait(masterDataSourceProperties.getMaxWait());
        datasource.setMaxActive(masterDataSourceProperties.getMaxActive());
        datasource.setMinEvictableIdleTimeMillis(masterDataSourceProperties.getMinEvictableIdleTimeMillis());
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    public DataSource read() {
        System.out.println("注入Read数据源!!!");
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(readDataSourceProperties.getUrl());
        datasource.setDriverClassName(readDataSourceProperties.getDriverClassName());
        datasource.setUsername(readDataSourceProperties.getUsername());
        datasource.setPassword(readDataSourceProperties.getPassword());
        datasource.setInitialSize(readDataSourceProperties.getInitialSize());
        datasource.setMinIdle(readDataSourceProperties.getMinIdle());
        datasource.setMaxWait(readDataSourceProperties.getMaxWait());
        datasource.setMaxActive(readDataSourceProperties.getMaxActive());
        datasource.setMinEvictableIdleTimeMillis(readDataSourceProperties.getMinEvictableIdleTimeMillis());
        try {
            datasource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return datasource;
    }

    @Bean
    public DynamicDataSource dynamicDataSource() {
        //主动实例化主库和读库数据源
        //为了防止spring注入异常,所以master和read都是主动实例化的,并不是交给spring管理
        this.setProperties();
        DataSource master = master();
        DataSource read = read();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DynamicDataSource.DatabaseType.Master, master);
        targetDataSources.put(DynamicDataSource.DatabaseType.Read, read);

        //将实例化的数据源放入动态数据源配置
        System.out.println("配置动态数据源!!!");
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        //因为事务问题,所以配置的master
        dataSource.setDefaultTargetDataSource(master);//设置默认数据源
        System.out.println("-----------  DataBaseConfigurationEnd  -----------");
        return dataSource;
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pbh</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <!--spring boot 组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--为了方便升级,Spring Boot 发布了一个新的 spring-boot-properties-migrator 模块。
        只要将其作为依赖添加到项目中,它不仅会分析应用程序的环境并在启动时打印诊断信息,
        而且还会在运行时为项目临时迁移属性。在您的应用程序迁移期间,这个模块是必备的。
        注意:迁移完成之后,请确保从项目的依赖关系中移除该模块。-->
       <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-properties-migrator</artifactId>
        </dependency>-->
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>-->
        <!-- spring boot 热部署插件 -->
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>-->

        <!-- mysql connector java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Apache的StringUtils -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>

        <!-- 分页 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!--swagger -->
        <dependency>
            <groupId>com.battcn</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>2.0.6-RELEASE</version>
        </dependency>

        <!--mybatis通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--<dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
           &lt;!&ndash;建议使用最新版本,最新版本请从项目首页查找 &ndash;&gt;
            <version>4.0.4</version>
        </dependency>-->

        <!--如果不想每次都写private  final Logger logger = LoggerFactory.getLogger(XXX.class); 可以用注解@Slf4j -->
        <!--注解@Slf4j注入后找不到变量log,那就给IDE安装lombok插件 安装完成后重启IDEA -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <!--表明该包只在编译和测试的时候用 -->
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- spring boot 支持的Maven插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!-- generatorConfig.xml位置 -->
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

附上SpringBoot新特性
https://blog.csdn.net/yalishadaa/article/details/79400916
记录springboot从1.5.10升级到2.0.0过程中遇到的问题(上)
https://www.jianshu.com/p/81e2798d6dd1
SpringBoot gitHub 文档
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一种非常流行的Java开发框架,它提供了一种方便的方式来管理应用程序的配置文件。在Spring Boot应用程序中,通常会使用application.properties或者application.yml来存储配置信息。但是,在复杂的应用中,可能存在多个模块,每个模块都需要自己的配置文件。在这种情况下,如何跨模块读取配置文件? 首先,需要明确的是,在Spring Boot中,配置文件读取是通过SpringEnvironment接口来实现的。我们可以通过Environment对象来获取配置文件中定义的属性。因此,如果要跨模块读取配置文件,就需要在不同的模块中都能够访问到Environment对象。 解决这个问题的一个简单方法是,使用Spring Boot提供的@PropertySource注解。这个注解可以将指定的配置文件加载到Environment对象中。因此,我们只需要在每个模块中都添加一个与其他模块不同的配置文件,并在每个模块中使用@PropertySource注解来加载自己的配置文件,就可以实现跨模块读取配置文件的目的。 另外,Spring Boot还提供了一种更加高级的方式来管理配置文件,即使用Spring Cloud Config服务器。通过使用这种方式,在不同的模块中都可以通过统一的Config服务器来读取配置信息,避免了多个配置文件的冗杂。不过,这种方式需要额外的配置工作,适用于更加复杂的应用场景。 综上所述,跨模块读取配置文件可以通过在每个模块中使用@PropertySource注解来实现。同时,也可以考虑使用Spring Cloud Config服务器来管理配置信息,以提高整个应用的可维护性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值