首先针对于配置文件, SpringBoot 反对两种格局, 一个是 application.properties, 另一个是 application.yml. 同时 properties 的优先级要高于 yml.
properties 的写法如下,左侧为 xx.xx, 右侧为具体数值, 两头用 = 隔开 luban.test = 123
yml 的写法如下, 用冒号产生级别
luban :
test : 123
SpringBoot 举荐应用 YML 文件
读取配置文件有两种形式:
- @ConfigurationProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties(prefix = "luban")
@Accessors(chain = true)
@Setter
@Getter
public class ConfigConfig {
private String test;
@PostConstruct
public void test(){System.out.println(test);
}
}
- @Value + @Component
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class Config {@Value("${luban.test:}")
private String test;
@PostConstruct
public void getAll(){System.out.println(test);
}
}