1. 用 @Value 注解
直接可以在你要用到改配置文件信息的类里面进行
具体例子如下:
@Service
public class MyCommandService {
@Value("${name:unknown}")
private String name;
public String getMessage() {
return getMessage(name);
}
public String getMessage(String name) {
return “”;
}
}
2 .
@PropertySource("classpath:xxx.properties") 与 @Value 注解配合
@PropertySource 注解当前类,参数为对应的配置文件路径.
package com.yihaomen.springboot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:application.properties")
public class GlobalProperties {
@Value("${name}")
private String name;
@Value("${address}")
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3读取自定义配置文件中的配置信息
为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources目录下创建配置文件author.properties
resources/author.properties内容如下:
author.name=Solin author.age=22
创建管理配置的实体类:
package Solin.controller;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
//加上注释@Component,可以直接在其他地方使用@Autowired来创建其实例对象
@Component
@ConfigurationProperties(prefix = "author",locations = "classpath:author.properties")
public class MyWebConfig{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
注意:
在@ConfigurationProperties注释中有两个属性:
locations:指定配置文件的所在位置
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以author.开头)
使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。
创建测试Controller
package Solin.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ConfigController {
@Autowired
private MyWebConfig conf;
@RequestMapping("/test")
public @ResponseBody String test() {
return "Name:"+conf.getName()+"---"+"Age:"+conf.getAge();
}
}
注意:由于在Conf类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。