springboot读取配置文件的几种方式

最近一直在学springboot,发现读取application.properties配置文件的方式有很多种。就目前自己使用的这些进行总结,如有遗失,欢迎补充:

1.使用注解@Value进行获取

@Controller
public class HelloController {
	@Value("${book.author}")
	private String name;

    @ResponseBody
    @RequestMapping("testConfigM1")
	public String testConfigM1(ModelMap modelMap) {		
		return name;
	}
}


application.properties:
book.author=石红英

 springboot读取配置文件的几种方式_第1张图片

2.使用bean ,封装

场景在application.properties中有student.name,student.age等,现在使用bean将值映射到bean上

/***--application.properties-----****/
student.name=\u554A\u554A\u554A真没漂亮  //这里用了2种编码方式编写,请往下读
student.age=25


/***------bean------****/
@Component//交给spring管理
@ConfigurationProperties(prefix = "student")//将配置文件的值映射到类上使用;prefix = "student"表示映射前缀是student
public class StudentProperties {
    private String name;
    private Integer age;
//set,get方法
}

   /***------controller------****/
    @Controller
   public class HelloController {
    @Autowired
	private StudentProperties studentProperties;
    @ResponseBody
	@RequestMapping("testConfigM2")
	public String testConfigM2(){
		System.out.println(studentProperties.getName()+"-----"+studentProperties.getAge());
		return  studentProperties.getName();
	}
}

 

 

这里顺便提一句:application.properties 在程序读取过程中会以Unicode读,文件的编码需要动态设置下:File-settings-File encodeings 选中transparent native-to-ascii conversion;这样我们在编写application.properties时任何编码的都会动态编译成Unicode码(不会乱码也不方便输入中文查看);可在target-classes 找到application.properties文件打开查看即可发现student.name已经变成\u554A\u554A\u554A\u771F\u6CA1\u6F02\u4EAE

springboot读取配置文件的几种方式_第2张图片

3.使用Environment进行获取

@Controller
public class HelloController {
	@Autowired
	private Environment environment;

	@ResponseBody
	@RequestMapping("testConfigM3")
	public String testConfigM3(){
		return  environment.getProperty("name2");
	}
}

/**************application.properties*********************/
name2=白骨精

 

 目前我们工程中用的都是第三种,springboot小白,欢迎大神来指点补充

 

你可能感兴趣的:(springboot)