Springboot读取配置文件

对照着大佬的GitHub的springboot案例 学习的自我总结

1. 读取application.properties中的属性(本质是从环境Environment中读取)

  • 先在配置文件中添加属性
    这里写图片描述
    注意:springboot的application.properties文件默认ISO8859-1编码,所以我的中文打上它会默认编码为ISO8859-1,而如果把文件换成UTF-8的话再读取配置文件时会出现中文乱码,这是因为springboot读取配置文件默认解码方式是ISO8859-1.

  • 读取配置文件
    · 读取的方式有3种:1、通过@Value注解;2、通过@ConfigurationProperties;3、通过Environment对象。
    1、@Value注解方式

@Value("${user.city}")
String city1;

@Test
public void test1() {
    System.out.println(city1);//结果为zibo
}

  • 2、通过@ConfigurationProperties注解
package com.example.demo.conf;

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

/**
 * @ConfigurationProperties 注解用于读取Springboot环境(Environment)中的属性,value和prefix都是相同的,
 * 接收配置文件下符合前缀的所有属性
 * 
 * <p>需要在pom中添加spring-boot-configuration-processor,他用于为配置文件对象生成元数据</p>
 * 
 * @author hasee
 *
 */
@ConfigurationProperties("user")
@Component
public class AppConf {
    private String name;
    private String city;
    private int age;
    private String chinese;

    @Override
    public String toString() {
        return "AppConf [name=" + name + ", city=" + city + ", age=" + age + ", chinese=" + chinese + "]";
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getChinese() {
        return chinese;
    }
    public void setChinese(String chinese) {
        this.chinese = chinese;
    }
}

先创建一个配置类,使用@ConfigurationProperties@componet注解。然后使用时直接注入该对象即可

@Autowired
AppConf appConf;

/**
 * 在这里由于我的配置文件中的前缀为user,而环境中加载的user.name优先级高于配置文件中的
 * 所以会被覆盖,参数等级具体可以参考springboot文档
 */
@Test
public void test2() {
    System.out.println(appConf);//输出结果AppConf [name=hasee, city=zibo, age=18, chinese=小小王]
}

  • 3.通过Environment对象
@Autowired
Environment environment;

@Test
public void test5() {
    String name = environment.getProperty("user.name");
    String chinese = environment.getProperty("user.chinese");
    String age = environment.getProperty("user.age");

    System.out.printf("name=%s age=%s chinese=%s \n", name,age,chinese);
    //输出结果:name=hasee age=18 chinese=小小王 
}

2. 读取自定义配置文件中的属性
在开发之中我们不可能所有的配置属性都放到application配置文件中,所以我们需要自定义配置文件,然后读取使用

  • 先创建一个自定义配置文件 author.properties文件
    这里写图片描述

  • 再创建一个配置文件类,并使用@ConfigurationProperties@PropertySource@Component

package com.example.demo.conf;

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

/**
 * 读取自定义配置文件
 * @ConfigurationProperties 指定前缀
 * @PropertySource 指定配置文件位置
 * @author hasee
 *
 */
@ConfigurationProperties("author")
@PropertySource("classpath:author.properties")
@Component
public class OutConf {
    private String name;
    private String city;
    private int age;
    private String chinese;

    @Override
    public String toString() {
        return "OutConf [name=" + name + ", city=" + city + ", age=" + age + ", chinese=" + chinese + "]";
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getChinese() {
        return chinese;
    }
    public void setChinese(String chinese) {
        this.chinese = chinese;
    }
}

其中@ConfigurationProperties注解用于接收具有符合前缀的属性、@PropertySource指定自定义文件的位置、@componet将声明为组件,用于以后注入使用

  • 读取属性
@Autowired
OutConf outConf;

/**
* 读取自定义配置文件
 */
@Test
public void test3() {
    System.out.println(outConf);
    //运行结果:OutConf [name=wrr-author, city=zibo, age=18, chinese=小小王]
}

这里为什么会乱码呢,细心的朋友会发现我上面的author.properties文件中的chinese是小小王是中文的,那是因为我设置文件为UTF-8了,然后Springboot读取时候用的是ISO8859-1解码的,所以出现了乱码。

解决方法
可以在配置文件对象注入阶段先用ISO8859-1解码,然后再使用UTF-8进行编码,编码之后再注入。(将配置文件中setChinese()方法进行修改为如下

public void setChinese(String chinese) {
    String result;
    try {
        result = new String(chinese.getBytes("ISO8859-1"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        result = null;
        e.printStackTrace();
    }
    this.chinese = result;
}

3.读取配置文件创建一些公共类(如过去在xml里配置dataSource或者其他对象一样)
在这里我们以配置c3p0连接池为例子(ps:Springboot其实根本不需要如过去一样需要手动配置创建连接池对象,只需要设置spring.datasource.type配置属性即可)

  • 引入c3p0包、创建一个配置类,使用@Configuration声明为配置对象
package com.example.demo.conf;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * <b>这里从Environment中获取配置信息</b><br>
 * 配置其他数据源连接池,这里配置c3p0
 * 1、添加jdbc驱动、c3p0的jar包
 * @author hasee
 *
 */
@Configuration
public class DataSourceConf01 {
    @Autowired
    Environment environment;

    @Bean
    public DataSource getDataSource() throws Exception {

        String jdbcUrl = environment.getProperty("spring.datasource.url");
        String user = environment.getProperty("spring.datasource.username");
        String password = environment.getProperty("spring.datasource.password");

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(user);
        dataSource.setPassword(password);

        return dataSource;
    }

}

@Configuration@Bean配和使用,再方法上加@Bean注解使其声明返回对象组成为Spring组件,用于注入使用

  • 使用该对象
@Autowired
DataSource dataSource;

@Test
public void test4() throws SQLException {
    Connection connection = dataSource.getConnection();
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select * from user");

    while(resultSet.next()) {
        System.out.println(resultSet.getString("nickname"));
    }
}

结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值