Springcloud学习笔记38--读取 .properties 配置文件的工具类PropertyUtils和@ConfigurationProperties读取yaml文件中配置的数据库连接池druid属性

1.读取 .properties 配置文件的工具类PropertyUtils

项目中经常将一些配置信息放到properties文件中,读取非常方便,下面介绍几种java读取properties配置文件的方式。先看示例的properties文件:

通过jdk提供的java.util.Properties类,基于ClassLoder读取配置文件,实现properties文件的读取。

1.1 Properties类

public class Properties extends Hashtable<Object,Object>

此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这 两个方法,因为put方法不仅允许存入String类型的value,还可以存入Object类型的。因此java.util.Properties类提 供了getProperty()和setProperty()方法来操作属性文件,同时使用store或save(已过时)来保存属性值(把属性值写 入.properties配置文件)

1.1.1 load方法

public void load(InputStream inStream) throws IOException

从输入字节流读取属性列表(键和元素对)。

1.1.2 getProperty方法

public String getProperty(String key)

使用此属性列表中指定的键搜索属性。

1.2. 可根据不同的方式来获取InputStream

(1)通过当前类加载器的getResourceAsStream方法获取

InputStream inputStream=PropertyUtil.class.getClassLoader().getResourceAsStream("flep.properties");

(2)从文件获取

InputStream inStream = new FileInputStream(new File("filePath"));  

1.3.案例

源码:

package com.ttbank.flep.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author lucky
 * @Date 2021/12/7 18:15
 */
public class PropertyUtil {
    public static Properties properties;

    static {
        loadProperties();
    }

    synchronized private static void loadProperties() {
        properties=new Properties();
        InputStream inputStream=null;
        try {
            inputStream=PropertyUtil.class.getClassLoader().getResourceAsStream("flep.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getProperties(String key){
        if(properties==null){
            loadProperties();
        }
        return properties.getProperty(key);
    }

    public static void main(String[] args) {
        System.out.println(getProperties("name"));
    }
}

项目结构:

 控制台输出:

2.@ConfigurationProperties读取yaml文件中配置的属性

2.1 @Configuration、@ConfigurationProperties、@EnableConfigurationProperties

2.1.1 @Configuration

@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

  • @Configuration配置spring并启动spring容器
  • @Configuration启动容器+@Bean注册Bean
  • @Configuration启动容器+@Component注册Bean

使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

2.1.2 @Component和@Bean注解

(1)@Component

@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。

注意:如果一个类添加了@Component注解,则这个类可以使用@Autowired注解注入;

@Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。

两者的目的是一样的,都是注册bean到Spring容器中。

2.1.3 @ConfigurationProperties

有时候有这样子的情景,我们想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了,这时候,我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类。

注意:一般和@Component配合使用;因为@ConfigurationProperties并不会将一个类标记为Spring的Component。请使用@Component注解标记该类,这样它就可以工作了。请注意,只有被标记为Component的类才能够被注入。

2.1.4 @EnableConfigurationProperties

@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的类生效。

如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。

2.2 入门案例

(1)在配置文件中配置如下信息:

flep:
  cluster_name: cluster5
  subsys_code: STPM
  contentId: 10000001

(2)定义一个实体类在装载配置文件信息

@Component
@ConfigurationProperties(prefix = "flep")
@Data
public class FileUaProperties {

    private String clusterName;

    private String subsysCode;

    private String contentId;

}

(3)在controller中进行实际使用测试。

/**
 * @Author lucky
 * @Date 2022/1/18 15:43
 */
@Slf4j
@RestController
@RequestMapping("/test/properties")
public class ConfigurationPropertiesController{
    @Autowired
    FileUaProperties fileUaProperties;

    @PostMapping("/getProperties")
    public void getProperties(){
        log.info(fileUaProperties.getClusterName());
        log.info(fileUaProperties.getSubsysCode());
        log.info(fileUaProperties.getContentId());
    }
}

控制台输出:

注意:

(1) @ConfigurationProperties 和 @value 有着相同的功能,但是 @ConfigurationProperties的写法更为方便。当需要注入多个前缀的内容考虑使用@Value注解

(2) @ConfigurationProperties 的 POJO类的命名比较严格,因为它必须和prefix的后缀名要一致, 不然值会绑定不上, 特殊的后缀名是“driver-class-name”这种带横杠的情况,在POJO里面的命名规则是 下划线转驼峰 就可以绑定成功

 2.3 配置数据库连接池DruidDataSource

(1)在配置文件中配置如下信息:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource

    #druid连接池配置
    druid:
      url: jdbc:mysql://localhost:3306/day1?serverTimezone=Asia/Shanghai&useSSL=false
      username: root
      password: plj***
      driver-class-name: com.mysql.cj.jdbc.Driver
      #初始化连接大小
      initial-size: 5
      #最大连接池数量
      max-active: 20
      #最小连接池数量
      min-idle: 3
      #配置获取连接等待超时时间,单位毫秒
      max-wait: 60000
      #配置间隔多久才进行一次检查看,检查需要关闭的空闲连接,单位毫秒
      time-between-eviction-runs-millis: 60000
      #配置一个连接在池中最小的生存时间,单位毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: select 'x'
      #建议配置为true,不影响性能,并且保证安全性,申请连接的时候检测
      test-while-idle: true
      #获取连接时执行检测,建议关闭,影响性能
      test-on-borrow: false
      #归还连接时执行检测,建议关闭,影响性能
      test-on-return: false
      #检测连接是否有效的超时时间
      validation-query-timeout: 10

(2)定义一个实体类在装载配置文件信息

这个类中的每个注解用处说明:

@Data 生成get/set方法

@Component 将这个类交给spring容器管理,这样就可以用@autowired注解自动注入

@ConfigurationProperties 读取yaml文件的属性项,将这些属性值设置到spring 管理的这个类的bean中

package com.ttbank.flep.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author lucky
 * @Date 2022/3/31 10:22
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DataSourceProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private int initialSize;
    private int minIdle;
    private int maxActive=100;
    private long maxWait;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    
}

 (3)数据库连接池配置类

package com.ttbank.flep.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author lucky
 * @Date 2022/4/1 9:18
 */
@Configuration
public class DruidConfig {
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean
    public DataSource druidDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setInitialSize(dataSourceProperties.getInitialSize());
        druidDataSource.setMinIdle(dataSourceProperties.getMinIdle());
        druidDataSource.setMaxActive(dataSourceProperties.getMaxActive());
        druidDataSource.setMaxWait(dataSourceProperties.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(dataSourceProperties.getValidationQuery());
        druidDataSource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow());
        druidDataSource.setTestOnReturn(dataSourceProperties.isTestOnReturn());

        try {
            druidDataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return druidDataSource;
    }

}

(4)debug模式启动项目

参考文献:

https://www.cnblogs.com/sebastian-tyd/p/7895182.html

https://www.cnblogs.com/s3189454231s/p/5626557.html

https://www.cnblogs.com/liaojie970/p/8043150.html----@ConfigurationProperties推荐。

https://www.jianshu.com/p/7f54da1cb2eb---推荐

https://blog.csdn.net/weixin_44313584/article/details/109393005---详解@Configuration注解

posted @ 2021-12-07 19:31  雨后观山色  阅读(1183)  评论(0编辑  收藏  举报