-- 从properties文件中获取信息
1 创建文件对象 private static Properties config = new Properties();
2 加载文件对象 config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("配置文件的名字"))
3 根据key获取value config.getProperty(key)
-- 示例
public class ConfigTest {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String ip = properties.getProperty("ip");
System.out.println(ip);
}
}
-- 示例二
ResourceBundle properties = ResourceBundle.getBundle("config");
System.out.println(properties.getString("ip"));
- 三种方式获取yml配置文件数据
1 在配置文件中写好连接数据库的信息 application.yml
2 通过注解来获取配置信息
@Value("${spring.datasource.username}")
private String username;
2
@Autowired
private Environment environment;
3 通过实体类配置
@Autowired
private Config config;
4 启动项目 测试数据
@RequestMapping("/config")
@ResponseBody
public String config(){
System.out.println("近啦");
System.out.println("username"+username);
String property = environment.getProperty("spring.datasource.password");
System.out.println("property"+property);
String type = config.getType();
System.out.println("type"+type);
return username+property+type;
}
- 实体类
@Component
@ConfigurationProperties(prefix = "spring.datasource")
@Data
public class Config {
private String url;
private String password;
private String username;
private String type;
}