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

Spring boot 配置文件

2016-07-27 21:28 309 查看

配置方式

sprint boot
现在支持的配置方式个人学到现在觉得无非就是在
classpath
路径下的
application.properties
来实现。贴一些默认的spring boot 选项。

默认配置

默认配置

自定义配置

如果想要自定义实体类,实现简单配置,有两种方式,一种是直接在默认的
application.properties
中实现,另一种是自己定义
properties
文件来实现,这就涉及文件加载路径的问题。下面具体来看看如何实现。

application.properties
中:

在默认的配置文件中,添加想要配置的属性,最好起一个前缀,这样也可以很好的支持
yaml
的配置文件。例如:

// 这里前缀定义为config , 有三个属性
config.environment:dev
config.session:true
config.maxTime:60


创建Bean

@ConfigurationProperties(prefix = "config")
@Component  // 或者 @Service @Controller @Repository 都行,只要能被spring扫描到加载进容器即可,默认的的spring boot bean 加载路径是在启动类所在包以及子包下,因此在创建文件的时候需要注意放在这些目录下。
public class Myconfig{
private String environment;
private boolean session;
private String maxTime;

public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}

public boolean isSession() {
return session;
}

public void setSession(boolean session) {
this.session = session;
}

public String getMaxTime() {
return maxTime;
}

public void setMaxTime(String maxTime) {
this.maxTime = maxTime;
}

@Override
public String toString() {
return this.environment+" : "+this.maxTime+" : "+this.session;
}
}


测试是否装配成功

@Autowired
Myconfig mc; //注入Myconfig实例
@Test
public void myconfig(){
System.out.println(mc.toString());
}


输出

dev : 60 : true


这样就实现了在默认的配置文件中添加我们自定义的配置信息。

在自定义文件中(example.properties):

创建自定义配置文件

config.environment:dev
config.session:true
config.maxTime:80


创建Bean

@Configuration  //使用configuration注解
@PropertySource( value = "classpath:example.properties") //指明加载路径
public class Myconfig{
@Value("${config.environment}")  //@Value("${}")获取配置文件中的属性
private String environment;
@Value("${config.session}")
private boolean session;
@Value("${config.maxTime}")
private String maxTime;

public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}

public boolean isSession() {
return session;
}

public void setSession(boolean session) {
this.session = session;
}

public String getMaxTime() {
return maxTime;
}

public void setMaxTime(String maxTime) {
this.maxTime = maxTime;
}

@Override
public String toString() {
return this.environment+" : "+this.maxTime+" : "+this.session;
}
}


测试是否装配成功

@Autowired
Myconfig mc; //注入Myconfig实例
@Test
public void myconfig(){
System.out.println(mc.toString());
}


输出

dev : 80 : true


至此,spring boot 中的一些简单的配置就实现了。刚开始接触
spring boot
,有理解上的错误,欢迎指正,交流学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot