Java项目中加载properties文件的方式

application.properties文件:
jdbc.username2=root
jdbc.password2=123456

一、Java程序环境

Java可以直接读取Properties文件,Properties类继承自HashTable,实际是将文件内容解析到一个Map中。

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

public class PropertiesOfJava {
    public static void main(String[] args) {
        try (InputStream inputStream = PropertiesOfJava.class.getClassLoader().getResourceAsStream("application.properties");) {
            Properties properties = new Properties();
            properties.load(inputStream);
            Object username = properties.get("jdbc.username");
            Object password = properties.get("jdbc.password");
            System.out.println(username);
            System.out.println(password);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

二、Spring环境

Spring 读取Properties文件的方式需要借助@PropertySource和@Value注解,@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")相当于<context:property-placeholder location="classpath:application.properties" file-encoding="UTF-8"/>配置,@Value注解是将properties属性注入到bean属性中。

@Configuration
@ComponentScan(basePackages = {"com.fan.spring.properties"})
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
public class PropertiesOfSpring {
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertiesOfSpring.class);
        PropertiesOfSpring properties = applicationContext.getBean(PropertiesOfSpring.class);
        System.out.println(properties.getUsername());
        System.out.println(properties.getPassword());
    }
}

三、Spring Boot环境

springboot下使用@ConfigurationProperties注解,默认加载application.properties文件的内容,也可以使用@PropertySource加载指定properties的内容。

@Component
@ConfigurationProperties(prefix = "jdbc")
public class Datasource {
    private String username;
    private String password;

    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;
    }
}

 

posted @ 2021-12-05 14:05  哲雪君!  阅读(542)  评论(0编辑  收藏  举报