您的位置:首页 > 编程语言 > Java开发

SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

2017-09-24 13:13 786 查看



SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

<div class="article_manage clearfix">
<div class="article_l">
<span class="link_categories">
标签:
<a href="http://www.csdn.net/tag/%e5%ba%94%e7%94%a8" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">应用</a><a href="http://www.csdn.net/tag/spring" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">spring</a>
</span>
</div>
<div class="article_r">
<span class="link_postdate">2017-04-22 15:04</span>
<span class="link_view" title="阅读次数">6898人阅读</span>
<span class="link_comments" title="评论次数"> <a href="#comments" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_pinglun'])">评论</a>(3)</span>
<span class="link_collect tracking-ad" data-mod="popu_171"> <a href="javascript:void(0);" onclick="javascript:collectArticle('SpringBoot%e9%9d%9e%e5%ae%98%e6%96%b9%e6%95%99%e7%a8%8b+%7c+%e7%ac%ac%e4%ba%8c%e7%af%87%ef%bc%9aSpring+Boot%e9%85%8d%e7%bd%ae%e6%96%87%e4%bb%b6%e8%af%a6%e8%a7%a3','70437576');return false;" title="收藏" target="_blank">收藏</a></span>
<span class="link_report"> <a href="#report" onclick="javascript:report(70437576,2);return false;" title="举报">举报</a></span>

</div>
</div>    <style type="text/css">
.embody{
padding:10px 10px 10px;
margin:0 -20px;
border-bottom:solid 1px #ededed;
}
.embody_b{
margin:0 ;
padding:10px 0;
}
.embody .embody_t,.embody .embody_c{
display: inline-block;
margin-right:10px;
}
.embody_t{
font-size: 12px;
color:#999;
}
.embody_c{
font-size: 12px;
}
.embody_c img,.embody_c em{
display: inline-block;
vertical-align: middle;
}
.embody_c img{
width:30px;
height:30px;
}
.embody_c em{
margin: 0 20px 0 10px;
color:#333;
font-style: normal;
}
</style>
<script type="text/javascript">
$(function () {
try
{
var lib = eval("("+$("#lib").attr("value")+")");
var html = "";
if (lib.err == 0) {
$.each(lib.data, function (i) {
var obj = lib.data[i];
//html += '<img src="' + obj.logo + '"/>' + obj.name + "  ";
html += ' <a href="' + obj.url + '" target="_blank">';
html += ' <img src="' + obj.logo + '">';
html += ' <em><b>' + obj.name + '</b></em>';
html += ' </a>';
});
if (html != "") {
setTimeout(function () {
$("#lib").html(html);
$("#embody").show();
}, 100);
}
}
} catch (err)
{ }

});
</script>
<div class="category clearfix">
<div class="category_l">
<img src="http://static.blog.csdn.net/images/category_icon.jpg">
<span>分类:</span>
</div>
<div class="category_r">
<label onclick="GetCategoryArticles('6830966','forezp','top','70437576');">
<span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">springboot<em>(26)</em></span>
<img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
<img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
<div class="subItem">
<div class="subItem_t"><a href="http://blog.csdn.net/forezp/article/category/6830966" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
<ul class="subItem_l" id="top_6830966">
</ul>
</div>
</label>
</div>
</div>
<div class="bog_copyright">
<p class="copyright_p">版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接 ,博主地址:http://blog.csdn.net/forezp。</p>
</div>


目录(?)[+]
一自定义属性
二将配置文件的属性赋给实体类
三自定义配置文件
四多个环境配置文件
五参考文献
优秀文章推荐

转载请标明出处:

http://blog.csdn.net/forezp/article/details/70437576

本文出自方志朋的博客

springboot采纳了建立生产就绪Spring应用程序的观点。 Spring Boot优先于配置的惯例,旨在让您尽快启动和运行。在一般情况下,我们不需要做太多的配置就能够让spring boot正常运行。在一些特殊的情况下,我们需要做修改一些配置,或者需要有自己的配置属性。

一、自定义属性

当我们创建一个springboot项目的时候,系统默认会为我们在src/main/java/resources目录下创建一个application.properties。个人习惯,我会将application.properties改为application.yml文件,两种文件格式都支持。

在application.yml自定义一组属性:

my:
name: forezp
age: 12
1
2
3
4


[/code]

如果你需要读取配置文件的值只需要加@Value(“${属性名}”):

@RestController
public class MiyaController {

@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;

@RequestMapping(value = "/miya")
public String miya(){
return name+":"+age;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14


[/code]

启动工程,访问:localhost:8080/miya,浏览器显示:

forezp:12

二、将配置文件的属性赋给实体类

当我们有很多配置属性的时候,这时我们会把这些属性作为字段来创建一个javabean,并将属性值赋予给他们,比如:

my:
name: forezp
age: 12number:  ${random.int}
uuid : ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: hi,i'm ${my.name}
1
2
3
4
5
6
7
8
9


[/code]

其中配置文件中用到了${random} ,它可以用来生成各种不同类型的随机值。

怎么讲这些属性赋于给一个javabean 呢,首先创建一个javabean :

@ConfigurationProperties(prefix = "my")
@Component
public class ConfigBean {

private String name;
private int age;
private int number;
private String uuid;
private int max;
private String value;
private String greeting;

省略了getter setter....
1
2
3
4
5
6
7
8
9
10
11
12
13
14


[/code]

需要加个注解@ConfigurationProperties,并加上它的prrfix。另外@Component可加可不加。另外spring-boot-configuration-processor依赖可加可不加,具体原因不详。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
1
2
3
4
5
6


[/code]

另外需要在应用类或者application类,加EnableConfigurationProperties注解。

@RestController
@EnableConfigurationProperties({ConfigBean.class})
public class LucyController {
@Autowired
ConfigBean configBean;

@RequestMapping(value = "/lucy")
public String miya(){
return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax();
}
1
2
3
4
5
6
7
8
9
10
11
12
13


[/code]

启动工程,访问localhost:8080/lucy,我们会发现配置文件信息读到了。

三、自定义配置文件

上面介绍的是我们都把配置文件写到application.yml中。有时我们不愿意把配置都写到application配置文件中,这时需要我们自定义配置文件,比如test.properties:

com.forezp.name=forezp
com.forezp.age=12
1
2
3


[/code]

怎么将这个配置文件信息赋予给一个javabean呢?

@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.forezp")
public class User {
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


[/code]

在最新版本的springboot,需要加这三个注解。@Configuration

@PropertySource(value = “classpath:test.properties”)

@ConfigurationProperties(prefix = “com.forezp”);在1.4版本需要

PropertySource加上location。

@RestController
@EnableConfigurationProperties({ConfigBean.class,User.class})
public class LucyController {
@Autowired
ConfigBean configBean;

@RequestMapping(value = "/lucy")
public String miya(){
return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax();
}

@Autowired
User user;
@RequestMapping(value = "/user")
public String user(){
return user.getName()+user.getAge();
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


[/code]

启动工程,打开localhost:8080/user;浏览器会显示:

forezp12

四、多个环境配置文件

在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.properties,其中{profile}对应你的环境标识,比如:

application-test.properties:测试环境

application-dev.properties:开发环境

application-prod.properties:生产环境

怎么使用?只需要我们在application.yml中加:

spring:
profiles:
active: dev
1
2
3
4


[/code]

其中application-dev.yml:

server:
port: 8082
1
2
3


[/code]

启动工程,发现程序的端口不再是8080,而是8082。

源码下载:https://github.com/forezp/SpringBootLearning

五、参考文献

spring-boot-reference-guide-zh

pring Boot干货系列:(二)配置文件解析

Spring Boot属性配置文件详解

优秀文章推荐:

更多springboot 教程:springBoot非官方教程 | 文章汇总

更多springcoud 教程:史上最简单的 SpringCloud 教程 | 文章汇总

(function () {('pre.prettyprint code').each(function () {
var lines = (this).text().split(′\n′).length;varnumbering = $('').addClass('pre-numbering').hide();
(this).addClass(′has−numbering′).parent().append(numbering);
for (i = 1; i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: