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

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

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

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

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

通过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.2getProperty方法

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 classPropertyUtil {
    public staticProperties properties;

    static{
        loadProperties();
    }

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

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

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

项目结构:

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

控制台输出:

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

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 classFileUaProperties {

    privateString clusterName;

    privateString subsysCode;

    privateString contentId;

}

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

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

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

控制台输出:

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

注意:

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

免责声明:文章转载自《Springcloud学习笔记38读取 .properties 配置文件的工具类PropertyUtils和@ConfigurationProperties读取yaml文件中配置的数据库连接池druid属性》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇干货分享:ASP.NET CORE(C#)与Spring Boot MVC(JAVA)异曲同工的编程方式总结Linux学习之iostat命令详解下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Eclipse properties配置文件中文乱码设置

1. eclipse中properties的默认编码为 ISO-8859-1, 输入汉字会被转换为unicode 2. 点击 Windows-->preferences 按下图找到更改编码位置 3. 调整编码为 UTF-8 , 点击update, 点击Apply and Close 4. 完成...

A component required a bean of type 'com.example...' that could not be found解决办法

工程启动报错A component required a bean of type ‘com.example…’ that could not be found 解决办法一:1、再启动类添加mapper包扫描注解即可@MapperScan(“com.example.firstspringboot.dao”) 解决办法二:在每个mapper接口上添加@m...

No fallback instance of type class found for feign client user-service(转)

1、错误日志 在 feign 开启熔断,配置 fallback 类,实现当前接口的实现类时,报错信息如下: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. ERROR 7204...

实战角度比较EJB2和EJB3的架构异同

】     EJB编程模型的简化     首先,EJB3简化的一个主要表现是:在EJB3中,一个EJB不再象EJB2中需要两个接口一个Bean实现类,虽然我们以前使用JBuilder这样可视化开发工具自动生成了EJB2的这三个类,好像不觉得复杂,但是当EJB个数增加时,就显得累赘了。     简化后的EJB3的sessionBean依靠annotation...

shiro的单机版 和 集群版

在我们的开发当中 我们一般权限都是个 比较繁琐 但又必不可少的 一部分 【不管我们的 数据库设计 还是我们采用何种技术 我们的权限库表 大多都是大同小异 业务逻辑也是如此】 在我们不使用任何框架的时候 我们也是可以做到 但是细节过于麻烦 在很多时候 都是重复造轮子的过程 所以出现了 很多开源比较休息的额权限框架如:shiro Spring security...

Java 实时论坛

简介 Sym 是一个用 Java 写的实时论坛,欢迎来体验! 初衷 Sym 的诞生是有如下几点原因: 我们想实现一种新的网络社区体验,独立博客+社区互动 大多数论坛用户体验不够现代化,想做一个和聊 QQ 一样体验的论坛 已有的用 Java 写的论坛真的很少/丑,并且大多已经不再维护 基本理念 实时交互 在浏览帖子时,传统论坛都是需要刷新页面来查看回帖的。...