springboot加载外部xml_springboot加载外部配置⽂件
⽹上搜集和整理如下(⾃⼰已验证过)
1. war包在tomcat中加载外部配置⽂件
war包运⾏在独⽴tomcat下时,如何加载war包外部配置application.properties,以达到每次更新war包⽽不⽤更新配置⽂件的⽬的。
SpringBoot配置⽂件可以放置在多种路径下,不同路径下的配置优先级有所不同。
可放置⽬录(优先级从⾼到低)
1.file:./config/ (当前项⽬路径config⽬录下);
2.file:./ (当前项⽬路径下);
3.classpath:/config/ (类路径config⽬录下);
4.classpath:/ (类路径config下).
json格式转换为txt格式优先级由⾼到底,⾼优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载配置⽂件并互补配置;
想要满⾜不更新配置⽂件的做法⼀般会采⽤1 和 2,但是这些对于运⾏在独⽴tomcat下的war包并不⽐作⽤。
我这⾥采⽤的是SpringBoot的Profile配置。
在application.properties中增加如下配置:
spring.profiles.active=test1
properties文件用什么打开再在tomcat根⽬录下新建⼀个名为config的⽂件夹,新建⼀个名为application-test1.properties的配置⽂件。
完成该步骤后,Profile配置已经完成了。
然后还需要将刚刚新建的config⽂件夹添加到tomcat的classpath中。
打开tomcat中catalina.properties⽂件,在common.loader处添加**${catalina.home}/config**,此处的config即之前新建的⽂件夹名称。
tabletennis造句
如此,⼤功告成。程序启动之后,每次配置⽂件都会从config/application-test1.properties加载。
2.⾃定义配置⽂件
如果你不想使⽤application.properties作为配置⽂件,怎么办?完全没问题
java -jar myproject.jar --fig.location=classpath:/default.properties,classpath:/override.properties
或者
java -jar -fig.location=D:\config\config.properties springbootrestdemo-0.0.1-SNAPSHOT.jar
当然,还能在代码⾥指定
@SpringBootApplication
@PropertySource(value={"file:config.properties"})public classSpringbootrestdemoApplication {public static
voidmain(String[] args) {
SpringApplication.run(SpringbootrestdemoApplication.class, args);
}
}
3.(扩展)这⾥详细介绍下spring.profiles.active
默认配置 src/main/resources/application.properties
app.window.width=500
app.window.height=400
指定具体环境的配置
src/main/resources/application-dev.properties
app.window.height=300column公式的含义
src/main/resources/application-prod.properties
app.window.width=600
app.window.height=700
简单的应⽤
package ample;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class ClientBean {
@Value("${app.window.width}")
private int width;
@Value("${app.window.height}")
private int height;
@PostConstruct
private void postConstruct() {
System.out.printf("width= %s, height= %s%n", width, height);
}
}
package ample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class ExampleMain {
public static void main(String[] args) {
SpringApplication.run(ExampleMain.class, args);
}
round取整是四舍五入吗}
运⾏
$ mvn spring-boot:run
important的所有词性width= 500, height= 400
$ mvn -Dspring.profiles.active=dev spring-boot:run width= 500, height= 300
$ mvn -Dspring.profiles.active=prod spring-boot:run width= 600, height= 700

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。