Properties - Javateappl/Java-Training GitHub Wiki

Java 读取配置文件 配置文件有2种。

  1. Xxx.properties 一般默认的为application.properties or application.yml 可以通过@Value读取。

@Value可以有3种方式赋值

  • 通过在Value中指定内容来赋值

@value(“hello”)

Public String word;

这时word的内容就是hello

  • 通过value指定properties中的变量名来赋值

@value(“${port}”)

Public String port;

Port的内容就是properties文件中对应port的值。

package com.example.demo.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:application.properties")
public class TestProperties {
    @Value("sam")
    public String name;

    @Value("${port}")
    public String port;

    @Override
    public String toString() {
        return "TestProperties{" +
                "name='" + name + '\'' +
                ", port='" + port + '\'' +
                '}';
    }
}

通过这种方式读取值时,需要使用@PropertySource来指定properties文件的路径。

配置文件一般放在src\main\resources目录下