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=石红英

 

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

3.使用Environment进行获取

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

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

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

 

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

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值