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注解

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

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

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

2.1.3 @ConfigurationProperties

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

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里面的命名规则是 下划线转驼峰 就可以绑定成功

参考文献:

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注解

原文地址:https://www.cnblogs.com/luckyplj/p/15657912.html