Spring Boot之配置文件

Spring Boot默认的配置文件为application.properties,放在src/main/resources目录下或者类路径的/config目录下,作为Spring Boot的全局配置文件,对一些默认的配置进行修改。

接下来使用例子展示Spring Boot配置文件的用法:

首先在src/main/resources下新建application.properties文件,内容如下

author.name=微儿博客
author.sex=男

创建controller类

ackage com.springboot.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//不需要指定配置文件的位置,因为使用的默认的配置文件
@RestController
public class DemoController {
	
	@Value("${author.name}")//注入配置文件中的值
	private String name;
	@Value("${author.sex}")
	private String sex;
	
	@RequestMapping("/")
	public String index(){
		return name + ":" + sex;
	}
}

创建入口类

package com.springboot.properties;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

执行:

微儿博客

那么如何使用其他的配置文件呢?

新建author.properties,内容如下:

person.name=weare
person.sex=man

修改DemoController为:

@RestController
@PropertySource("classpath:author.properties")//指定配置文件
public class DemoController {
	
	@Value("${person.name}")
	private String name;
	@Value("${person.sex}")
	private String sex;
	
	@RequestMapping("/")
	public String index(){
		return name + ":" + sex;
	}
}

运行,如图

微儿个人博客

上例中属性都是通过@Value逐个注入的,但是如果注入的属性很多就会很麻烦,接下来使用@ConfigurationProperties将配置文件属性和Bean的属性关联

创建Author类:

package com.springboot.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component//声明这是一个Bean
@ConfigurationProperties(prefix="author")//指定配置文件中的前缀
public class Author {
	
	private String name;
	
	private String sex;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
}

修改DemoController类:

@RestController
@ConfigurationProperties
public class DemoController {
	
	@Autowired
	private Author author;
	
	@RequestMapping("/")
	public String index(){
		return author.getName() + ":" + author.getSex();
	}
}

运行App类,结果如下图:

微儿博客

更多信息请访问微儿博客,或者搜索微儿博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值