spring boot application properties配置详解
- 格式:pdf
- 大小:71.39 KB
- 文档页数:12
多环境配置(1)非主配置的取名时为application-字符串.propertites 在主配置中调用时就是spring.profiles.active=字符串dev 开发online 上线test 测试(2)激活的配置中没有的属性还可以在主配置中配置但是激活配置和主配置都有的情况下,看激活配置。
激活配置为主,主配置为辅自定义配置第一种方法:使用@Value来实现获取值properties文件:=上海location.address=青浦Controller中:@RestControllerpublic class ConfigController {@Value("${}")private String name;@Value("${location.address}")private String address;@RequestMapping("config")public String hello(){return name+" "+ address;}}这样在控制器中个就可以获取properties文件中的配置第二种方法:使用创建类和@ConfigurationProperties 注解properties文件:=上海location.address=青浦创建一个对应的类:ConfigInfo@Component//指该类是一个主件,相当于把该类实例化到Spring容器中,相当于配置文件中<bean id="" class=""> ,加了这个,在其他类中就可以使用Autowired注解了@ConfigurationProperties(prefix = "location")//同类的配置信息自动封装成实体类public class ConfigInfo {private String name;private String address;...get set方法...}控制器:@Autowiredprivate ConfigInfo configInfo;再使用这个对象。
解决SpringBoot加载application.properties配置⽂件的坑SpringBoot加载application.properties配置⽂件的坑事情的起因是这样的⼀次,本⼈在现场升级程序,升级完成后进⾏测试,结果接⼝调⽤都报了这么个错误:⼤概意思是https接⼝需要证书校验,这就奇怪了,项⽬启动加载的是包外的application.properties配置⽂件,配置⽂件⾥没有配置使⽤https啊。
本⼈马上检查了下包内的application.properties配置⽂件,发现包内确实配置了https相关的配置项:明明包外的配置⽂件优先级⾼于包内的,为啥包内的⼀部分配置项起作⽤了呢,我们了解的配置⽂件优先级是这样的:这是为啥呢?后来才了解到除了⾼优先级覆盖低优先级外,还有⼀条重要的规则:如有不同内容,⾼优先级和低优先级形成互补配置。
这下才恍然⼤悟,我包外的配置⽂件⾥把https相关的配置项注释掉了,相当于没有这个配置项,但是包内的配置⽂件有,根据互补原则,包内的这⼏个配置项起作⽤了。
问题原因找到了,如何解决呢?要不我把包内的那⼏个配置项也注释掉,重新打个包?其实不必这么⿇烦,通过-Dspring.config.location命令直接指定包外的配置⽂件就可以了,试了下,果然没有问题了。
问题虽然解决了,但是还有些疑问,为啥指定包外的配置⽂件后就不存在互补情况了呢?通过阅读springboot相关源码,找到了答案:⼤概意思是:如果-Dspring.config.location指定了配置⽂件,则只加载指定的那⼀个配置⽂件,如果没有专门指定配置⽂件则遍历包外、包内相关的配置⽂件,按照⾼优先级覆盖低优先级和互补原则进⾏加载。
弄明⽩这些问题后,实地部署项⽬的时候,保险起见还是通过-Dspring.config.location命令直接指定加载的配置⽂件⽐较好,避免出现⼀些不必要的⿇烦。
Spring Boot加载application.properties探究基于Spring Boot的多Module项⽬中,有许多公共的配置项,为避免在每个接⼊层都配置⼀遍,⼀个设想是在公共依赖的Module的application.properties(application.yml)中进⾏配置。
springboot加载application配置⽂件源码分析springboot加载application.yml和application.properties原理监听器:ConfigFileApplicationListener、BootstrapApplicationListener1、系统启动时,调⽤SpringApplication.run()2、初始化监听器//初始化SpringApplicationRunListeners,并且初始化变量listeners,将EventPublishingRunListener存放与listeners中1)SpringApplicationRunListeners listeners = this.getRunListeners(args);2)3)SpringFactoriesLoader.loadSpringFactories()加载META-INF/spring.factories下的配置监听器3、调⽤ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);内部调⽤步骤如下1)listeners.environmentPrepared((ConfigurableEnvironment)environment);监听器的准备⼯作2)listener.environmentPrepared(environment);循环listeners中的监听器,执⾏environmentPrepared⽅法,其中加载配置⽂件的监听器就在循环列表中3)执⾏EventPublishingRunListener中的environmentPrepared()⽅法public void environmentPrepared(ConfigurableEnvironment environment) {this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));}4)SimpleApplicationEventMulticaster类中的doInvokeListener()⽅法5)执⾏ConfigFiledApplicationListerner类中的onApplicationEvent(event)⽅法6)执⾏ConfigFileApplicationListener中的onApplicationEnviromentPrepareEvent()⽅法private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {List<EnvironmentPostProcessor> postProcessors = this.loadPostProcessors();postProcessors.add(this);AnnotationAwareOrderComparator.sort(postProcessors);Iterator var3 = postProcessors.iterator();while(var3.hasNext()) {EnvironmentPostProcessor postProcessor = (EnvironmentPostProcessor)var3.next();postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());}}注意:AnnotationAwareOrderComparator.sort(postProcessors); 对List<EnvironmentPostProcessor>集合进⾏排序,排序规则按照spring中的注解@Order注解和@Priority注解排序7)迭代postPrccessors集合,并且执⾏集合中的postProcessEnvironment⽅法,重点看ConfigFileApplicationListener类中的postProcessEnvironment⽅法其中会添加⼀个属性源进来ResourceLoader8)调⽤load⽅法加载属性protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {RandomValuePropertySource.addToEnvironment(environment);(new ConfigFileApplicationListener.Loader(environment, resourceLoader)).load();}9) load⽅法中调⽤apply⽅法void load() {FilteredPropertySource.apply(this.environment, DEFAULT_PROPERTIES, LOAD_FILTERED_PROPERTY,(defaultProperties) -> {this.profiles = new LinkedList<>();this.processedProfiles = new LinkedList<>();this.activatedProfiles = false;this.loaded = new LinkedHashMap<>();initializeProfiles();while (!this.profiles.isEmpty()) {Profile profile = this.profiles.poll();if (isDefaultProfile(profile)) {addProfileToEnvironment(profile.getName());}load(profile, this::getPositiveProfileFilter,addToLoaded(MutablePropertySources::addLast, false));this.processedProfiles.add(profile);}load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true));addLoadedPropertySources();applyActiveProfiles(defaultProperties);});}10) apply⽅法默认获取defaultProperties属性,如果获取为空,则从上⼀步中执⾏函数式编程中的accept⽅法,下边移步到accept⽅法⼀探究竟,⾸先apply⽅法中会执⾏⼀个初始化⽅法initializeProfiles,⽅法中会向profiles中放⼊null,然后再放⼊⼀个"default",⽤来从外部遍历,遍历为null的时候,加载springboot的默认配置,遍历为“default"时,加载⽤户配置,从⽽充分体现了约定⼤于配置11)遍历profiles集合,遍历的第⼀次为null,执⾏load⽅法如下private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {getSearchLocations().forEach((location) -> {boolean isDirectory = location.endsWith("/");Set<String> names = isDirectory ? getSearchNames() : NO_SEARCH_NAMES;names.forEach((name) -> load(location, name, profile, filterFactory, consumer));});}⾸先执⾏getSearchLocations⽅法,获取默认的路径,默认的路径为如果启动参数中有"spring.config.location",则加载spring.config.location中指定的配置⽂件,否则⽤默认的DEFAULT_SEARCH_LOCATIONS,classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/12)取出Locations为classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/遍历set,按照先后顺序取配置⽂件13)获取配置⽂件名字,如果配置的话,则去配置的名字,否则⽤默认的"application"14)取到location和name之后,执⾏load(String location, String name, Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer)⽅法,加载配置,如下图15 最终通过以钩⼦程序的形式调⽤函数式编程完成属性的赋值调⽤Map中的computeIfAbsent,如果不存在profile的key,则添加新的数据,并将value值返回。
application.properties多环境配置⽂件、jar包外部配置⽂件、配置项加。
⼀、简介spring boot项⽬application.properties⽂件存放及使⽤介绍⼆、⽅法⼀多环境配置⽂件我们⼀般都会有多个应⽤环境,开发环境、测试环境、⽣产环境,各个环境的配置会略有不同,我可以根据这个创建多份配置⽂件,由主配置⽂件来控制读取那个⼦配置创建spring boot项⽬后可以同时创建多个.properties⽂件,只要符合它要求的格式即可格式:application-{profile}.properties;{profile}是变量⽤于⾃定义配置⽂件名称分别创建三个应⽤环境的配置和⼀个主配置1、application.properties 主配置(以下是配置内容,这⾥的dev就是其他配置⽂件的标识名dev、test、prod)# 具体使⽤那个配置⽂件的标识名称(格式:application-{profile}.properties;{profile}是变量⽤于⾃定义配置⽂件名称)spring.profiles.active=dev2、application-dev.properties 开发环境(以下是配置内容)=tyh-demo-prop# 开发环境端⼝server.port=100013、application-test.properties 测试环境(以下是配置内容)=tyh-demo-prop# 测试环境端⼝server.port=100024、application-prod.properties ⽣产环境(以下是配置内容)=tyh-demo-prop# ⽣产环境端⼝server.port=10003更改主配置中的spring.profiles.active=dev这个参数就可以切换不同⼦配置⽂件了由于此⽅法.properties⽂件依然在jar中,我们修改时并不⽅便,⽽且太多信息暴露在开发中容易泄露,所以结合⽅法⼆进⾏使⽤三、⽅法⼆jar包外部配置⽂件我们在开发完成发布⽣产环境时往往都会修改⼀下配置⽂件的相关内容,⽽默认.properties配置⽂件会被封装到jar包中修改起来不⽅便,所以spring boot给了⼏个读取配置⽂件的位置,我们可以通过这个⽅式去从jar包外部修改配置⽂件⼀般我们会将.properties放在resources⽂件夹内spring boot会按以下顺序去寻找配置⽂件1、“当前⽬录”的/config⽂件夹下2、“当前⽬录”下3、classpath的/config⽂件夹下4、classpath下以下是图例解释:当找到配置⽂件后将不会再继续寻找,也就说该⽂件优先级以下的配置⽂件将不会被读取,找到即停⽌“当前⽬录”指的是我们打成可执⾏jar包后,⼀般会⽤bat⽂件来启动,这个当前⽬录指的就是bat⽂件的⽬录我们常规存放的位置就是优先级最低的位置,所以我们只需要再单独拷贝⼀份配置⽂件,放在bat的“当前⽬录”即可四、配置项加密我们的application.properties⽂件中会有很多敏感信息,如:数据库连接、缓存服务器连接等等,这些⽤户名密码都应该是外部不可见的,所以最好将其加密后存储我们使⽤jasypt来进⾏加解密,⾸先先建⽴项⽬,我搭建了spring boot项⽬1、添加pom.xml信息<!-- 配置⽂件项加密 --><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>2.1.0</version></dependency>2、在application.properties⽂件中增加配置项,需要jasypt来解密的密⽂需要⽤“ENC(......)”括起来=tyh-demo-propserver.port=10001# 配置⽂件项加解密密码,此处注释,⽽放在代码中(放在代码中使加密密钥和密⽂分开)#jasypt.encryptor.password=112233# 模拟数据库连接帐号密码ername=ENC(nm3F96GtUIwZUHzsP0Mp1A==)spring.datasource.password=ENC(lmn7lAlePy1hZu505WO0xQ==)3、程序启动类,默认jasypt的密钥是放在配置⽂件中但这样会导致密⽂和密钥都在配置⽂件中,所以我把密钥放在程序中@SpringBootApplicationpublic class App {public static void main(String[] args) {//设置配置⽂件项加密密钥(放在这⾥使加密密钥和密⽂分开)System.setProperty("jasypt.encryptor.password", "112233");SpringApplication.run(App.class, args);}}4、使⽤注解的⽅式来注⼊配置⽂件中的配置项import org.springframework.beans.factory.annotation.Value;import ponent;@Componentpublic class SysConfig {@Value("${ername}")private String dbUsername;@Value("${spring.datasource.password}")private String dbPassword;//⾃⼰⽣成get set⽅法}5、编写controller及action来调⽤⼀下import com.tyh.demo.prop.config.SysConfig;import org.jasypt.encryption.StringEncryptor;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("/test")public class TestController {@AutowiredStringEncryptor encryptor;@ResponseBody@RequestMapping("/index")public String index() {return encryptor.encrypt("taiyonghai");}@AutowiredSysConfig sysConfig;@ResponseBody@RequestMapping("/getConfig")public SysConfig getConfig() {//spring boot⾃动注⼊就会将密⽂解密return sysConfig;}}由于其使⽤的是PBEWithMD5AndDES加密⽅式,所以每次加密出来的结果都不⼀样,所以很适合对数据进⾏加密运⾏后,可以看到⾃动解密的配置项五、配置项注⼊静态static与⾮静态属性我们有很多编码需求需要使⽤.properties⽂件中⾃定义的配置项,传统使⽤Properties对象来操作,类似如下代码,这种⽅式太过灵活我们不想使⽤的配置项可能也会被提取出来,⽽且当我们不想使⽤jar包内的配置⽂件,⽽是利⽤优先级使⽤外部的,这种直接读取的⽅式就很不⽅便,所以推荐使⽤@Value的⽅式来使⽤public class SysConfigUtil {private static Properties props;static {try {// TODO:读取⽤户配置Resource resource = new ClassPathResource("/application.properties");props = PropertiesLoaderUtils.loadProperties(resource);} catch (IOException e) {e.printStackTrace();}}public static String getProperty(String key) {return props == null ? null : props.getProperty(key);}}还是刚才的项⽬,使⽤@Value来注⼊想让程序使⽤的配置项,⽽不想让程序使⽤的就不注⼊,这样来使配置项可控1、我们在.properties⽂件中增加两个⾃定义配置项=tyh-demo-propserver.port=10001# 配置⽂件项加解密密码,此处注释,⽽放在代码中(放在代码中使加密密钥和密⽂分开)#jasypt.encryptor.password=112233# 模拟数据库连接帐号密码ername=ENC(nm3F96GtUIwZUHzsP0Mp1A==)spring.datasource.password=ENC(lmn7lAlePy1hZu505WO0xQ==)# 模拟其他⾃定义配置项#tyh.url.web.admin=tyh.url.web.agent=2、@Value注⼊可以给静态属性也可以给⾮静态属性,具体根据使⽤场景⾃⾏决定,如果配置项可能不存在也可以设置默认值,避免程序⽆法启动@Componentpublic class SysConfig {@Value("${ername}")private String dbUsername;@Value("${spring.datasource.password}")private String dbPassword;/*⾮静态属性注⼊(注⼊属性)*///@Value的参数代表配置项的key,如果没有启动会报错,加上“:”为其设置默认值即可解决冒号后⾯的就是默认值内容,也可以直接:冒号后⾯空⽩就是空 @Value("${tyh.url.web.admin:}")private String urlAdmin;//###⾃⼰创建get/set⽅法###/*静态属性注⼊(注⼊set()⽅法)*///使⽤@Component把当前类当作组件启动时注⼊该静态属性值,静态属性注⼊set()⽅法public static String urlAgent;@Value("${tyh.url.web.agent:}")private void setUrlAgent(String urlAgent) {SysConfig.urlAgent = urlAgent;}}3、使⽤时⾮静态属性使⽤Autowired注⼊,静态属性直接取值//⾮静态属性注⼊取值(必须使⽤Autowired注⼊)@AutowiredSysConfig sysConfig;public void test() {//静态属性注⼊取值(直接获取)String str = SysConfig.urlAgent;}推荐使⽤@Value来注⼊配置项进⾏使⽤,便与后续接⼊Apollo等配置管理中⼼进⾏配置统⼀管理。
springboot启动如何修改application.properties的参数⽬录修改application.properties的参数1、⽅法⼀:直接在cmd中执⾏2、⽅法⼆:配置3、⽅法三4、⽅法四springboot项⽬启动参数以下⼏种⽅式都可以被@Value读取到1、java -jar -Dserver.port=8888 -Xms1024m demo.jar2、java -jar demo.jar --server.port=88883、从操作系统的环境变量中读取4、通过项⽬中配置⽂件bootstrap/application⽂件载⼊修改application.properties的参数1、⽅法⼀:直接在cmd中执⾏java -jar xxx.jar --server.port:8082如果要修改多个参数,空格后继续写就可以了。
再例如:java -jar xxx.jar --server.port:8082 =xxx2、⽅法⼆:配置3、⽅法三4、⽅法四springboot 有读取外部配置⽂件的⽅法,如下优先级:第⼀种是在jar包的同⼀⽬录下建⼀个config⽂件夹,然后把配置⽂件放到这个⽂件夹下。
第⼆种是直接把配置⽂件放到jar包的同级⽬录。
第三种在classpath下建⼀个config⽂件夹,然后把配置⽂件放进去。
第四种是在classpath下直接放配置⽂件。
我们通常在src/main/resources ⽂件夹下创建的application.properties ⽂件的优先级是最低的!1)内外都有配置⽂件,配置⽂件读取是有优先级,外配置⽂件优于内配置⽂件读取。
2)如果内配置⽂件⾥有外配置⽂件没有的配置,那两者互补。
⽐如外配置⽂件没有配置数据库,内配置⽂件⾥配置了数据库,那内配置⽂件的配置会被使⽤。
3)如果内配置⽂件⾥和外配置⽂件⾥都有相同的配置,⽐如两者都配置了数据库,但是两个连接的不同,那外配置⽂件会覆盖内配置⽂件⾥的配置。
SpringBoot(⼀)SpringBootApplication注解详解@SpringBootApplicationSpringBootApplication注解我们肯定不会陌⽣,在配置SpringBoot的启动类时就会⽤到这个注解,下⾯就说⼀下SpringBootApplication注解的详细作⽤@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })打开SpringBootApplication注解我们可以看到在注解下包含以上三个注解,那么简单说明下以上三个注解的具体作⽤1.@Configuration:⽤于定义⼀个配置类2.@EnableAutoConfiguration :Spring Boot会⾃动根据你jar包的依赖来⾃动配置项⽬。
3.@ComponentScan:告诉Spring 哪个packages 的⽤注解标识的类会被spring⾃动扫描并且装⼊bean容器。
在我们初学SpringBoot的时候我们可能都会遇到⼀个问题,就是定义了⼀个请求,但是SpringBoot并没有装配成功,导致请求失败代码如下(1) 启动类代码:@SpringBootApplication@ComponentScanpublic class HelloWorldMainApplication {public static void main(String[] args) {SpringApplication.run(HelloWorldMainApplication.class, args);}}(2)请求1代码@Controllerpublic class HelloController {@ResponseBody@RequestMapping("/hello")public String Hello(){return "Hello World";}}(2)请求2代码@Controllerpublic class TestController {@ResponseBody@RequestMapping("/test")public String Test(){return "Hello Test";}}(3)⽬录结构从上图的⽬录结构我们可以看到请求1HelloController所在的⽬录是跟HelloWorldMainApplication启动类属于同级⽬录,⽽请求2TestController所在⽬录是com包下也就是请求1和启动类的⽗级⽬录,下⾯启动项⽬并发送请求看下结果(4)控制台(5)请求1(6)请求2其实从控制台我们就可以看到hello请求是被Spring扫描到⽽test请求并没有被扫描到,所以test请求肯定会出现404请求失败这种结果,那么SpringBoot为什么只能扫描同级⽬录和⼦集⽬录呢?如果我们想扫描指定⽬录下的⽂件该怎么做,看下图public void registerBeanDefinitions(AnnotationMetadata metadata,BeanDefinitionRegistry registry) {register(registry, new PackageImport(metadata).getPackageName());}这段代码就是SpringBoot在启动类中默认扫描包路径的配置,所在路径(点击@SpringBootApplication注解---点击@EnableAutoConfiguration注解---点击@AutoConfigurationPackage---点击@Import(AutoConfigurationPackages.Registrar.class)),其实看到这个⽅法名我们应该不会感到陌⽣,因为Spring载⼊IOC容器的⽅法不就是BeanDefinition么,SpringBoot是基于Spring的所以这点就不难理解了从上图我们可以看到所得到的值是com.main也就可以说明为什么@SpringBootApplication默认扫描同级以及⼦级⽬录,⽽test请求在⽗级⽬录所以扫描不到请求⾃然会出现404的错误,那么如何扫描指定⽬录的包呢?看下⾯代码@ComponentScan(basePackages = {"com"})@SpringBootApplication(scanBasePackages = {"com"})这俩种⽅式都可以扫描指定⽬录下的包,多个包⽤逗号分隔即可。
Springboot默认配置⽂件application.properties的常见配置属性#SPRING CONFIG(ConfigFileApplicationListener) =#配置⽂件名(默认为 'application' )spring.config.location =#配置⽂件的位置#多环境配置⽂件激活属性spring.profiles.active=dev #加载application-dev.properties配置⽂件内容application-dev.properties:#开发环境application-test.properties:#测试环境application-prod.properties:#⽣产环境#activemqspring.activemq.broker-url #指定ActiveMQ broker的URL,默认⾃动⽣成.spring.activemq.in-memory #是否是内存模式,默认为true.spring.activemq.password #指定broker的密码.spring.activemq.pooled #是否创建PooledConnectionFactory,⽽⾮ConnectionFactory,默认falseer #指定broker的⽤户.#aopspring.aop.auto #是否⽀持@EnableAspectJAutoProxy,默认为: truespring.aop.proxy-target-class #true为使⽤CGLIB代理,false为JDK代理,默认为false#applicationspring.application.admin.enabled #是否启⽤admin特性,默认为: falsespring.application.admin.jmx-name #指定admin MBean的名称,默认为: org.springframework.boot:type=Admin,name=SpringApplication#artemis(HornetQ捐献给apache后的版本)spring.artemis.embedded.cluster-password #指定集群的密码,默认是启动时随机⽣成.spring.artemis.embedded.data-directory #指定Journal⽂件的⽬录.如果不开始持久化则不必要指定.spring.artemis.embedded.enabled #是否开启内嵌模式,默认truespring.artemis.embedded.persistent #是否开启persistent store,默认false.spring.artemis.embedded.queues #指定启动时创建的队列,多个⽤逗号分隔,默认: []spring.artemis.embedded.server-id #指定Server ID. 默认是⼀个⾃增的数字,从0开始.spring.artemis.embedded.topics #指定启动时创建的topic,多个的话逗号分隔,默认: []spring.artemis.host #指定Artemis broker 的host. 默认: localhostspring.artemis.mode #指定Artemis 的部署模式, 默认为auto-detected(也可以为native or embedded).spring.artemis.port #指定Artemis broker 的端⼝,默认为: 61616#autoconfigspring.autoconfigure.exclude #配置要排除的Auto-configuration classes.#batchspring.batch.initializer.enabled #是否在必要时创建batch表,默认为truespring.batch.job.enabled #是否在启动时开启batch job,默认为trues #指定启动时要执⾏的job的名称,逗号分隔,默认所有job都会被执⾏spring.batch.schema #指定要初始化的sql语句路径,默认:classpath:org/springframework/batch/core/schema-@@platform@@.sql)spring.batch.table-prefix #指定批量处理的表的前缀.#cookie、session配置ment #指定session cookie的commentserver.session.cookie.domain #指定session cookie的domainserver.session.cookie.http-only #是否开启HttpOnly.server.session.cookie.max-age #设定session cookie的最⼤age. #设定Session cookie 的名称.server.session.cookie.path #设定session cookie的路径.server.session.cookie.secure #设定session cookie的“Secure” flag.server.session.persistent #重启时是否持久化session,默认falseserver.session.timeout #session的超时时间server.session.tracking-modes #设定Session的追踪模式(cookie, url, ssl).#datasourcespring.dao.exceptiontranslation.enabled #是否开启PersistenceExceptionTranslationPostProcessor,默认为truespring.datasource.abandon-when-percentage-full #设定超时被废弃的连接占到多少⽐例时要被关闭或上报spring.datasource.allow-pool-suspension #使⽤Hikari pool时,是否允许连接池暂停,默认为: falsespring.datasource.alternate-username-allowed #是否允许替代的⽤户名.spring.datasource.auto-commit #指定updates是否⾃动提交.spring.datasource.catalog #指定默认的catalog.mit-on-return #设置当连接被归还时,是否要提交所有还未完成的事务spring.datasource.connection-init-sql #指定连接被创建,再被添加到连接池之前执⾏的sql.spring.datasource.connection-init-sqls #使⽤DBCP connection pool时,指定初始化时要执⾏的sqlspring.datasource.connection-properties.[key] #在使⽤DBCP connection pool时指定要配置的属性spring.datasource.connection-test-query #指定校验连接合法性执⾏的sql语句spring.datasource.connection-timeout #指定连接的超时时间,毫秒单位.spring.datasource.continue-on-error #在初始化数据库时,遇到错误是否继续,默认falsespring.datasource.data #指定Data (DML)脚本spring.datasource.data-source-class-name #指定数据源的全限定名.spring.datasource.data-source-jndi #指定jndi的地址spring.datasource.data-source-properties.[key] #使⽤Hikari connection pool时,指定要设置的属性spring.datasource.db-properties #使⽤Tomcat connection pool,指定要设置的属性spring.datasource.default-auto-commit #是否⾃动提交.spring.datasource.default-catalog #指定连接默认的catalog.spring.datasource.default-read-only #是否设置默认连接只读.spring.datasource.default-transaction-isolation #指定连接的事务的默认隔离级别.spring.datasource.driver-class-name #指定driver的类名,默认从jdbc url中⾃动探测.spring.datasource.fair-queue #是否采⽤FIFO返回连接.spring.datasource.health-check-properties.[key] #使⽤Hikari connection pool时,在⼼跳检查时传递的属性spring.datasource.idle-timeout #指定连接多久没被使⽤时,被设置为空闲,默认为10msspring.datasource.ignore-exception-on-pre-load #当初始化连接池时,是否忽略异常.spring.datasource.init-sql #当连接创建时,执⾏的sqlspring.datasource.initial-size #指定启动连接池时,初始建⽴的连接数量spring.datasource.initialization-fail-fast #当创建连接池时,没法创建指定最⼩连接数量是否抛异常spring.datasource.initialize #指定初始化数据源,是否⽤data.sql来初始化,默认: truespring.datasource.isolate-internal-queries #指定内部查询是否要被隔离,默认为falsespring.datasource.jdbc-interceptors #使⽤Tomcat connection pool时,指定jdbc拦截器,分号分隔spring.datasource.jdbc-url #指定JDBC URL.spring.datasource.jmx-enabled #是否开启JMX,默认为: falsespring.datasource.jndi-name #指定jndi的名称.spring.datasource.leak-detection-threshold #使⽤Hikari connection pool时,多少毫秒检测⼀次连接泄露.spring.datasource.log-abandoned #使⽤DBCP connection pool,是否追踪废弃statement或连接,默认为: falsespring.datasource.log-validation-errors #当使⽤Tomcat connection pool是否打印校验错误.spring.datasource.login-timeout #指定连接数据库的超时时间.spring.datasource.max-active #指定连接池中最⼤的活跃连接数.spring.datasource.max-age #指定连接池中连接的最⼤年龄spring.datasource.max-idle #指定连接池最⼤的空闲连接数量.spring.datasource.max-lifetime #指定连接池中连接的最⼤⽣存时间,毫秒单位.spring.datasource.max-open-prepared-statements #指定最⼤的打开的prepared statements数量.spring.datasource.max-wait #指定连接池等待连接返回的最⼤等待时间,毫秒单位.spring.datasource.maximum-pool-size #指定连接池最⼤的连接数,包括使⽤中的和空闲的连接.spring.datasource.min-evictable-idle-time-millis #指定⼀个空闲连接最少空闲多久后可被清除.spring.datasource.min-idle #指定必须保持连接的最⼩值(For DBCP and Tomcat connection pools)spring.datasource.minimum-idle #指定连接维护的最⼩空闲连接数,当使⽤HikariCP时指定. #指定数据源名.spring.datasource.num-tests-per-eviction-run #指定运⾏每个idle object evictor线程时的对象数量spring.datasource.password #指定数据库密码.spring.datasource.platform #指定schema要使⽤的Platform(schema-${platform}.sql),默认为: allspring.datasource.pool-name #指定连接池名字.spring.datasource.pool-prepared-statements #指定是否池化statements.spring.datasource.propagate-interrupt-state #在等待连接时,如果线程被中断,是否传播中断状态.spring.datasource.read-only #当使⽤Hikari connection pool时,是否标记数据源只读spring.datasource.register-mbeans #指定Hikari connection pool是否注册JMX MBeans.spring.datasource.remove-abandoned #指定当连接超过废弃超时时间时,是否⽴刻删除该连接.spring.datasource.remove-abandoned-timeout #指定连接应该被废弃的时间.spring.datasource.rollback-on-return #在归还连接时,是否回滚等待中的事务.spring.datasource.schema #指定Schema (DDL)脚本.spring.datasource.separator #指定初始化脚本的语句分隔符,默认: ;spring.datasource.sql-script-encoding #指定SQL scripts编码.spring.datasource.suspect-timeout #指定打印废弃连接前的超时时间.spring.datasource.test-on-borrow #当从连接池借⽤连接时,是否测试该连接.spring.datasource.test-on-connect #创建时,是否测试连接spring.datasource.test-on-return #在连接归还到连接池时是否测试该连接.spring.datasource.test-while-idle #当连接空闲时,是否执⾏连接测试.spring.datasource.time-between-eviction-runs-millis #指定空闲连接检查、废弃连接清理、空闲连接池⼤⼩调整之间的操作时间间隔spring.datasource.transaction-isolation #指定事务隔离级别,使⽤Hikari connection pool时指定spring.datasource.url #指定JDBC URL.e-disposable-connection-facade #是否对连接进⾏包装,防⽌连接关闭之后被使⽤.e-equals #⽐较⽅法名时是否使⽤String.equals()替换==.e-lock #是否对连接操作加锁ername #指定数据库名.spring.datasource.validation-interval #指定多少ms执⾏⼀次连接校验.spring.datasource.validation-query #指定获取连接时连接校验的sql查询语句.spring.datasource.validation-query-timeout #指定连接校验查询的超时时间.spring.datasource.validation-timeout #设定连接校验的超时时间,当使⽤Hikari connection pool时指定spring.datasource.validator-class-name #⽤来测试查询的validator全限定名.spring.datasource.xa.data-source-class-name #指定数据源的全限定名.spring.datasource.xa.properties #指定传递给XA data source的属性#data springdataspring.data.elasticsearch.cluster-name #指定es集群名称,默认: elasticsearchspring.data.elasticsearch.cluster-nodes #指定es的集群,逗号分隔,不指定的话,则启动client node.spring.data.elasticsearch.properties #指定要配置的es属性.spring.data.elasticsearch.repositories.enabled #是否开启es存储,默认为: truespring.data.jpa.repositories.enabled #是否开启JPA⽀持,默认为: truespring.data.mongodb.authentication-database #指定鉴权的数据库名spring.data.mongodb.database #指定mongodb数据库名spring.data.mongodb.field-naming-strategy #指定要使⽤的FieldNamingStrategy.spring.data.mongodb.grid-fs-database #指定GridFS database的名称.spring.data.mongodb.host #指定Mongo server host.spring.data.mongodb.password #指定Mongo server的密码.spring.data.mongodb.port #指定Mongo server port.spring.data.mongodb.repositories.enabled #是否开启mongodb存储,默认为truespring.data.mongodb.uri #指定Mongo database URI.默认:mongodb://localhost/testername #指定登陆mongodb的⽤户名.spring.data.rest.base-path #指定暴露资源的基准路径.spring.data.rest.default-page-size #指定每页的⼤⼩,默认为: 20spring.data.rest.limit-param-name #指定limit的参数名,默认为: sizespring.data.rest.max-page-size #指定最⼤的页数,默认为1000spring.data.rest.page-param-name #指定分页的参数名,默认为: pagespring.data.rest.return-body-on-create #当创建完实体之后,是否返回body,默认为falsespring.data.rest.return-body-on-update #在更新完实体后,是否返回body,默认为falsespring.data.rest.sort-param-name #指定排序使⽤的key,默认为: sortspring.data.solr.host #指定Solr host,如果有指定了zk的host的话,则忽略。
详解springboot使⽤application.properties进⾏外部配置application.properties⼤家都不陌⽣,我们在开发的时候,经常使⽤它来配置⼀些可以⼿动修改⽽且不⽤编译的变量,这样的作⽤在于,打成war包或者jar⽤于⽣产环境时,我们可以⼿动修改环境变量⽽不⽤再重新编译。
spring boot允许你⾃定义⼀个application.properties⽂件,然后放在以下的地⽅,来重写spring boot的环境变量或者定义你⾃⼰环境变量1. 当前⽬录的 “/config”的⼦⽬录下2. 当前⽬录下3. classpath根⽬录的“/config”包下4. classpath的根⽬录下1点和2点适合在⽣产环境下,例如,打包成可执⾏的jar包这⾥要注意,“当前⽬录”是指demo.jar包的⽬录下,要使配置⽂件⽣效,在使⽤Java -jar demo.jar的命令时,必须先路由到demo.jar 包的路径下,再使⽤其命名,3点和4点适合在开发环境下如果同时在四个地⽅都有配置⽂件,配置⽂件的优先级是从1到4。
使⽤配置⽂件之后,spring boo启动时,会⾃动把配置信息读取到spring容器中,并覆盖spring boot的默认配置,那么,我们怎么来读取和设置这些配置信息呢1.通过命令⾏来重写和配置环境变量,优先级最⾼,例如可以通过下⾯的命令来重写spring boot 内嵌tomcat的服务端⼝,注意“=”俩边不要有空格java -jar demo.jar --server.port=9000如果想要设置多个变量怎么办,可以已json的格式字符串来设置java -jar demo.jar --spring.application.json='{"foo":"bar"}'2.通过@value注解来读取@RestController@RequestMapping("/task")public class TaskController {@Value("${connection.remoteAddress}") private String address;@RequestMapping(value = {"/",""})public String hellTask(@Value("${ername}")String name){return "hello task !!";}}3.通过Environment接⼝来获取,只需要把接⼝注进去即可@RestController@RequestMapping("/task")public class TaskController {@Autowired Environment ev ;@Value("${connection.remoteAddress}") private String address;@RequestMapping(value = {"/",""})public String hellTask(@Value("${ername}")String name){String password = ev.getProperty("connection.password");return "hello task !!";}}4.可以⾃定义⼀个⼯具类,来获取,这种⽅式关键在于读取配置⽂件信息,适合⾃定义的配置信息,spring 容器默认的配置信息会读不到@Componentpublic class SystemConfig {private static Properties props ;public SystemConfig(){try {Resource resource = new ClassPathResource("/application.properties");//props = PropertiesLoaderUtils.loadProperties(resource);} catch (IOException e) {e.printStackTrace();}}/*** 获取属性* @param key* @return*/public static String getProperty(String key){return props == null ? null : props.getProperty(key);}/*** 获取属性* @param key 属性key* @param defaultValue 属性value* @return*/public static String getProperty(String key,String defaultValue){return props == null ? null : props.getProperty(key, defaultValue);}/*** 获取properyies属性* @return*/public static Properties getProperties(){return props;}}//⽤的话,就直接这样⼦String value = SystemConfig.getProperty("key");5.可以利⽤${…}在application.properties引⽤变量=springmyapp.desc=${} nice6.可以在application.properties配置随机变量,利⽤的是RandomValuePropertySource类my.secret=${random.value}my.number=${random.int}my.bignumber=${random.long}my.number.less.than.ten=${random.int(10)}my.number.in.range=${random.int[1024,65536]}简单的配置⽂件的使⽤就先写到这⾥,再看看其他⾼级⽤法,如Profiles还有@ConfigurationProperties 以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
SpringBoot中配置⽂件application.properties使⽤⼀、配置⽂档配置项的调⽤⼆、绑定对象bean调⽤有时候属性太多了,⼀个个绑定到属性字段上太累,官⽅提倡绑定⼀个对象的bean,这⾥我们建⼀个ConfigBean.java类,顶部需要使⽤注解@ConfigurationProperties(prefix = “com”)来指明使⽤哪个1 2 3 4 5 6 7@ConfigurationProperties(prefix = "com") public class ConfigBean {private String name;private String id;// 省略getter和setter}这⾥配置完还需要在spring Boot⼊⼝类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,在bean 类那边添加1 2 3 4 5 6 7 8@SpringBootApplication@EnableConfigurationProperties({ConfigBean.class}) public class Chapter2Application {public static void main(String[] args) {SpringApplication.run(Chapter2Application.class, args); }}最后在Controller中引⼊ConfigBean使⽤即可,如下:1 2 3 4 5 6 7 8 9 10@RestControllerpublic class UserController {@AutowiredConfigBean configBean;@RequestMapping("/")public String hexo(){return configBean.getName()+configBean.getId(); }}三、参数间引⽤在application.properties中的各个参数之间也可以直接引⽤来使⽤,就像下⾯的设置:1 2 ="张三"com.id="8"com.psrInfo=${}编号为${com.id}这样我们就可以只是⽤psrInfo这个属性就好四、使⽤⾃定义新建的配置⽂件 我们新建⼀个bean类,如下:1 2 3 4 5 6 7 8@Configuration@ConfigurationProperties(prefix = "com.md") @PropertySource("classpath:test.properties") public class ConfigTestBean {private String name;private String want;// 省略getter和setter}主要就是加了⼀个注解:@PropertySource("classpath:test.properties")五、配置⽂件优先级application.properties和application.yml⽂件可以放在⼀下四个位置:外置,在相对于应⽤程序运⾏⽬录的/congfig⼦⽬录⾥。
springboot项⽬application.properties配置⽂件⾥⾃定义⽇志输出demo:#配置⽇志输出类型#logging.pattern.console=%boldMagenta(%d{yyyy-MM-dd HH:mm:ss}) [%p] %highlight(%C:%L) : %m %n#有颜⾊的logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%p] %highlight(%C:%L) : %m%n#没有颜⾊的logging.pattern.console=%d %-5p %c:%line %m%n#配置全局输出级别logging.level.root=INFO#配置包的输出级别.springframework.web.servlet=ERROR#配置⽇志⽂件格式logging.pattern.file=%boldMagenta(%d{yyyy-MM-dd HH:mm:ss}) [%p] %highlight(%C:%L) : %m%n#开启⽀持ANSI格式输出,如果你的控制台可以⽀持ANSI,那么输出结果会⾼亮显⽰spring.output.ansi.enabled=ALWAYS# ⽇志⽂件最⼤⼤⼩logging.file.max-size=10MB# 默认该⽬录下会⽣成spring.log. logging.file.path 和 2选1,如果都配置,以后者为准#logging.file.path=D:/logs/# 默认该⽇志放在项⽬根⽬录下=D:/logs/my-project.logs# 只⽀持默认的Logback设置,不能配合其他⾃定义⽇志项使⽤#logging.pattern.rolling-file-name=${}.%d{yyyy-MM-dd}.%i.gzhibernate || JPA 打印SQL相关⽇志:# log content for sql parameters when config 'trace'.hibernate.type.descriptor.sql.BasicBinder=trace# log sql when config 'debug'.hibernate.type.descriptor.sql=debug# log content for sql result when config 'trace'.hibernate.type.descriptor.sql.BasicExtractor=infoend.。
#SPRING CONFIG(ConfigFileApplicationListener)=#config file name(default to'application')spring.config.location=#location of config file#PROFILESspring.profiles.active=#comma list of active profilesspring.profiles.include=#unconditionally activate the specified comma separated profiles#APPLICATION SETTINGS(SpringApplication)spring.main.sources=spring.main.web-environment=#detect by defaultspring.main.show-banner=truespring.main....=#see class for all properties#LOGGINGlogging.path=/var/logslogging.file=myapp.loglogging.config=#location of config file(default classpath:logback.xml for logback) logging.level.*=#levels for loggers, e.g.".springframework=DEBUG" (TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF)#IDENTITY(ContextIdApplicationContextInitializer)=spring.application.index=#EMBEDDED SERVER CONFIGURATION(ServerProperties)server.port=8080server.address=#bind to a specific NICserver.session-timeout=#session timeout in secondsserver.context-parameters.*=#Servlet context init parameters, e.g. server.context-parameters.a=alphaserver.context-path=#the context path,defaults to'/'server.servlet-path=#the servlet path,defaults to'/'server.ssl.enabled=true#if SSL support is enabledserver.ssl.client-auth=#want or needserver.ssl.key-alias=server.ssl.ciphers=#supported SSL ciphersserver.ssl.key-password=server.ssl.key-store=server.ssl.key-store-password=server.ssl.key-store-provider=server.ssl.key-store-type=server.ssl.protocol=TLSserver.ssl.trust-store=server.ssl.trust-store-password=server.ssl.trust-store-provider=server.ssl.trust-store-type=server.tomcat.access-log-pattern=#log pattern of the access logserver.tomcat.access-log-enabled=false#is access logging enabledserver.tomcat.internal-proxies=10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\192\\.168\\.\\d{1,3}\\.\\d{1,3}|\\169\\.254\\.\\d{1,3}\\.\\d{1,3}|\\127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}#regular expression matching trusted IP addressesserver.tomcat.protocol-header=x-forwarded-proto#front end proxy forward header server.tomcat.port-header=#front end proxy port headerserver.tomcat.remote-ip-header=x-forwarded-forserver.tomcat.basedir=/tmp#base dir(usually not needed,defaults to tmp)server.tomcat.background-processor-delay=30;#in secondsserver.tomcat.max-http-header-size=#maximum size in bytes of the HTTP message headerserver.tomcat.max-threads=0#number of threads in protocol handlerserver.tomcat.uri-encoding=UTF-8#character encoding to use for URL decoding#SPRING MVC(WebMvcProperties)spring.mvc.locale=#set fixed locale,e.g.en_UKspring.mvc.date-format=#set fixed date format,e.g.dd/MM/yyyyspring.mvc.message-codes-resolver-format=#PREFIX_ERROR_CODE/ POSTFIX_ERROR_CODEspring.mvc.ignore-default-model-on-redirect=true#If the the content of the"default" model should be ignored redirectsspring.view.prefix=#MVC view prefixspring.view.suffix=#...and suffixspring.resources.cache-period=#cache timeouts in headers sent to browserspring.resources.add-mappings=true#if default mappings should be added#SPRING HATEOS(HateoasProperties)spring.hateoas.apply-to-primary-object-mapper=true#if the primary mapper should also be configured#HTTP encoding(HttpEncodingProperties)spring.http.encoding.charset=UTF-8#the encoding of HTTP requests/responses spring.http.encoding.enabled=true#enable http encoding supportspring.http.encoding.force=true#force the configured encoding#JACKSON(JacksonProperties)spring.jackson.date-format=#Date format string(e.g.yyyy-MM-dd HH:mm:ss),or a fully-qualified date format class name(e.g.com.fasterxml.jackson.databind.util.ISO8601DateFormat)spring.jackson.property-naming-strategy=#One of the constants on Jackson's PropertyNamingStrategy(e.g. CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)or the fully-qualified class name of a PropertyNamingStrategy subclassspring.jackson.deserialization.*=#see Jackson's DeserializationFeaturespring.jackson.generator.*=#see Jackson's JsonGenerator.Featurespring.jackson.mapper.*=#see Jackson's MapperFeaturespring.jackson.parser.*=#see Jackson's JsonParser.Featurespring.jackson.serialization.*=#see Jackson's SerializationFeature#THYMELEAF(ThymeleafAutoConfiguration)spring.thymeleaf.check-template-location=truespring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.excluded-view-names=#comma-separated list of view names that should be excluded from resolutionspring.thymeleaf.view-names=#comma-separated list of view names that can be resolvedspring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html#;charset=<encoding>is addedspring.thymeleaf.cache=true#set to false for hot refresh#FREEMARKER(FreeMarkerAutoConfiguration)spring.freemarker.allow-request-override=falsespring.freemarker.cache=truespring.freemarker.check-template-location=truespring.freemarker.charset=UTF-8spring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.expose-spring-macro-helpers=falsespring.freemarker.prefix=spring.freemarker.request-context-attribute=spring.freemarker.settings.*=spring.freemarker.suffix=.ftlspring.freemarker.template-loader-path=classpath:/templates/#comma-separated list spring.freemarker.view-names=#whitelist of view names that can be resolved#GROOVY TEMPLATES(GroovyTemplateAutoConfiguration)spring.groovy.template.cache=truespring.groovy.template.charset=UTF-8spring.groovy.template.configuration.*=#See Groovy's TemplateConfigurationspring.groovy.template.content-type=text/htmlspring.groovy.template.prefix=classpath:/templates/spring.groovy.template.suffix=.tplspring.groovy.template.view-names=#whitelist of view names that can be resolved#VELOCITY TEMPLATES(VelocityAutoConfiguration)spring.velocity.allow-request-override=falsespring.velocity.cache=truespring.velocity.check-template-location=truespring.velocity.charset=UTF-8spring.velocity.content-type=text/htmlspring.velocity.date-tool-attribute=spring.velocity.expose-request-attributes=falsespring.velocity.expose-session-attributes=falsespring.velocity.expose-spring-macro-helpers=falsespring.velocity.number-tool-attribute=spring.velocity.prefer-file-system-access=true#prefer file system access for template loadingspring.velocity.prefix=spring.velocity.properties.*=spring.velocity.request-context-attribute=spring.velocity.resource-loader-path=classpath:/templates/spring.velocity.suffix=.vmspring.velocity.toolbox-config-location=#velocity Toolbox config location,for example "/WEB-INF/toolbox.xml"spring.velocity.view-names=#whitelist of view names that can be resolved#JERSEY(JerseyProperties)spring.jersey.type=servlet#servlet or filterspring.jersey.init=#init paramsspring.jersey.filter.order=#INTERNATIONALIZATION(MessageSourceAutoConfiguration)spring.messages.basename=messagesspring.messages.cache-seconds=-1spring.messages.encoding=UTF-8#SECURITY(SecurityProperties)=user#login usernameer.password=#login passworder.role=USER#role assigned to the usersecurity.require-ssl=false#advanced settings...security.enable-csrf=falsesecurity.basic.enabled=truesecurity.basic.realm=Springsecurity.basic.path=#/**security.filter-order=0security.headers.xss=falsesecurity.headers.cache=falsesecurity.headers.frame=falsesecurity.headers.content-type=falsesecurity.headers.hsts=all#none/domain/allsecurity.sessions=stateless#always/never/if_required/statelesssecurity.ignored=false#DATASOURCE(DataSourceAutoConfiguration&DataSourceProperties)=#name of the data sourcespring.datasource.initialize=true#populate using data.sqlspring.datasource.schema=#a schema(DDL)script resource referencespring.datasource.data=#a data(DML)script resource referencespring.datasource.sql-script-encoding=#a charset for reading SQL scriptsspring.datasource.platform=#the platform to use in the schema resource (schema-${platform}.sql)spring.datasource.continue-on-error=false#continue even if can't be initializedspring.datasource.separator=;#statement separator in SQL initialization scripts spring.datasource.driver-class-name=#JDBC Settings...spring.datasource.url=ername=spring.datasource.password=spring.datasource.jndi-name=#For JNDI lookup(class,url,username&password are ignored when set)spring.datasource.max-active=100#Advanced configuration...spring.datasource.max-idle=8spring.datasource.min-idle=8spring.datasource.initial-size=10spring.datasource.validation-query=spring.datasource.test-on-borrow=falsespring.datasource.test-on-return=falsespring.datasource.test-while-idle=spring.datasource.time-between-eviction-runs-millis=spring.datasource.min-evictable-idle-time-millis=spring.datasource.max-wait=spring.datasource.jmx-enabled=false#Export JMX MBeans(if supported)#DATASOURCE(PersistenceExceptionTranslationAutoConfigurationspring.dao.exceptiontranslation.enabled=true#MONGODB(MongoProperties)spring.data.mongodb.host=#the db hostspring.data.mongodb.port=27017#the connection port(defaults to27107)spring.data.mongodb.uri=mongodb://localhost/test#connection URLspring.data.mongodb.database=spring.data.mongodb.authentication-database=spring.data.mongodb.grid-fs-database=ername=spring.data.mongodb.password=spring.data.mongodb.repositories.enabled=true#if spring data repository support is enabled#JPA(JpaBaseConfiguration,HibernateJpaAutoConfiguration)spring.jpa.properties.*=#properties to set on the JPA connectionspring.jpa.open-in-view=truespring.jpa.show-sql=truespring.jpa.database-platform=spring.jpa.database=spring.jpa.generate-ddl=false#ignored by Hibernate,might be useful for other vendors spring.jpa.hibernate.naming-strategy=#naming classnamespring.jpa.hibernate.ddl-auto=#defaults to create-drop for embedded dbsspring.data.jpa.repositories.enabled=true#if spring data repository support is enabled#JTA(JtaAutoConfiguration)spring.jta.log-dir=#transaction log dirspring.jta.*=#technology specific configuration#SOLR(SolrProperties})spring.data.solr.host=http://127.0.0.1:8983/solrspring.data.solr.zk-host=spring.data.solr.repositories.enabled=true#if spring data repository support is enabled#ELASTICSEARCH(ElasticsearchProperties})spring.data.elasticsearch.cluster-name=#The cluster name(defaults to elasticsearch) spring.data.elasticsearch.cluster-nodes=#The address(es)of the server node (comma-separated;if not specified starts a client node)spring.data.elasticsearch.repositories.enabled=true#if spring data repository support is enabled#DATA RESET(RepositoryRestConfiguration})spring.data.rest.base-uri=#base URI against which the exporter should calculate its links#FLYWAY(FlywayProperties)flyway.check-location=false#check that migration scripts location existsflyway.locations=classpath:db/migration#locations of migrations scriptsflyway.schemas=#schemas to updateflyway.init-version=1#version to start migrationflyway.init-sqls=#SQL statements to execute to initialize a connection immediately after obtaining itflyway.sql-migration-prefix=Vflyway.sql-migration-suffix=.sqlflyway.enabled=trueflyway.url=#JDBC url if you want Flyway to create its own DataSourceer=#JDBC username if you want Flyway to create its own DataSource flyway.password=#JDBC password if you want Flyway to create its own DataSource#LIQUIBASE(LiquibaseProperties)liquibase.change-log=classpath:/db/changelog/db.changelog-master.yamlliquibase.check-change-log-location=true#check the change log location exists liquibase.contexts=#runtime contexts to useliquibase.default-schema=#default database schema to useliquibase.drop-first=falseliquibase.enabled=trueliquibase.url=#specific JDBC url(if not set the default datasource is used)er=#user name for liquibase.urlliquibase.password=#password for liquibase.url#JMXspring.jmx.enabled=true#Expose MBeans from Spring#RABBIT(RabbitProperties)spring.rabbitmq.host=#connection hostspring.rabbitmq.port=#connection portspring.rabbitmq.addresses=#connection addresses(e.g.myhost:9999,otherhost:1111) ername=#login userspring.rabbitmq.password=#login passwordspring.rabbitmq.virtual-host=spring.rabbitmq.dynamic=#REDIS(RedisProperties)spring.redis.database=#database namespring.redis.host=localhost#server hostspring.redis.password=#server passwordspring.redis.port=6379#connection portspring.redis.pool.max-idle=8#pool settings...spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1spring.redis.sentinel.master=#name of Redis serverspring.redis.sentinel.nodes=#comma-separated list of host:port pairs#ACTIVEMQ(ActiveMQProperties)spring.activemq.broker-url=tcp://localhost:61616#connection URLer=spring.activemq.password=spring.activemq.in-memory=true#broker kind to create if no broker-url is specified spring.activemq.pooled=false#HornetQ(HornetQProperties)spring.hornetq.mode=#connection mode(native,embedded)spring.hornetq.host=localhost#hornetQ host(native mode)spring.hornetq.port=5445#hornetQ port(native mode)spring.hornetq.embedded.enabled=true#if the embedded server is enabled(needs hornetq-jms-server.jar)spring.hornetq.embedded.server-id=#auto-generated id of the embedded server (integer)spring.hornetq.embedded.persistent=false#message persistencespring.hornetq.embedded.data-directory=#location of data content(when persistence is enabled)spring.hornetq.embedded.queues=#comma-separated queues to create on startup spring.hornetq.embedded.topics=#comma-separated topics to create on startup spring.hornetq.embedded.cluster-password=#customer password(randomly generated by default)#JMS(JmsProperties)spring.jms.jndi-name=#JNDI location of a JMS ConnectionFactoryspring.jms.pub-sub-domain=#false for queue(default),true for topic#Email(MailProperties)spring.mail.host=#mail server hostspring.mail.port=#mail server portername=spring.mail.password=spring.mail.default-encoding=UTF-8#encoding to use for MimeMessagesspring.mail.properties.*=#properties to set on the JavaMail session#SPRING BATCH(BatchDatabaseInitializer)s=job1,job2spring.batch.job.enabled=truespring.batch.initializer.enabled=truespring.batch.schema=#batch schema to load#AOPspring.aop.auto=spring.aop.proxy-target-class=#FILE ENCODING(FileEncodingApplicationListener)spring.mandatory-file-encoding=false#SPRING SOCIAL(SocialWebAutoConfiguration)spring.social.auto-connection-views=true#Set to true for default connection views or false if you provide your own#SPRING SOCIAL FACEBOOK(FacebookAutoConfiguration)spring.social.facebook.app-id=#your application's Facebook App IDspring.social.facebook.app-secret=#your application's Facebook App Secret#SPRING SOCIAL LINKEDIN(LinkedInAutoConfiguration)spring.social.linkedin.app-id=#your application's LinkedIn App IDspring.social.linkedin.app-secret=#your application's LinkedIn App Secret#SPRING SOCIAL TWITTER(TwitterAutoConfiguration)spring.social.twitter.app-id=#your application's Twitter App IDspring.social.twitter.app-secret=#your application's Twitter App Secret#SPRING MOBILE SITE PREFERENCE(SitePreferenceAutoConfiguration)spring.mobile.sitepreference.enabled=true#enabled by default#SPRING MOBILE DEVICE VIEWS(DeviceDelegatingViewResolverAutoConfiguration) spring.mobile.devicedelegatingviewresolver.enabled=true#disabled by defaultspring.mobile.devicedelegatingviewresolver.normal-prefix=spring.mobile.devicedelegatingviewresolver.normal-suffix=spring.mobile.devicedelegatingviewresolver.mobile-prefix=mobile/spring.mobile.devicedelegatingviewresolver.mobile-suffix=spring.mobile.devicedelegatingviewresolver.tablet-prefix=tablet/spring.mobile.devicedelegatingviewresolver.tablet-suffix=#----------------------------------------#ACTUATOR PROPERTIES#----------------------------------------#MANAGEMENT HTTP SERVER(ManagementServerProperties)management.port=#defaults to'server.port'management.address=#bind to a specific NICmanagement.context-path=#default to'/'management.add-application-context-header=#default to truemanagement.security.enabled=true#enable securitymanagement.security.role=ADMIN#role required to access the management endpoint management.security.sessions=stateless#session creating policy to use(always,never, if_required,stateless)#PID FILE(ApplicationPidFileWriter)spring.pidfile=#Location of the PID file to write#ENDPOINTS(AbstractEndpoint subclasses)endpoints.autoconfig.id=autoconfigendpoints.autoconfig.sensitive=trueendpoints.autoconfig.enabled=trueendpoints.beans.id=beansendpoints.beans.sensitive=trueendpoints.beans.enabled=trueendpoints.configprops.id=configpropsendpoints.configprops.sensitive=trueendpoints.configprops.enabled=trueendpoints.configprops.keys-to-sanitize=password,secret,key#suffix or regex endpoints.dump.id=dumpendpoints.dump.sensitive=trueendpoints.dump.enabled=trueendpoints.env.id=envendpoints.env.sensitive=trueendpoints.env.enabled=trueendpoints.env.keys-to-sanitize=password,secret,key#suffix or regexendpoints.health.id=healthendpoints.health.sensitive=trueendpoints.health.enabled=trueendpoints.health.mapping.*=#mapping of health statuses to HttpStatus codes endpoints.health.time-to-live=1000.id=info.sensitive=false.enabled=trueendpoints.mappings.enabled=trueendpoints.mappings.id=mappingsendpoints.mappings.sensitive=trueendpoints.metrics.id=metricsendpoints.metrics.sensitive=trueendpoints.metrics.enabled=trueendpoints.shutdown.id=shutdownendpoints.shutdown.sensitive=trueendpoints.shutdown.enabled=falseendpoints.trace.id=traceendpoints.trace.sensitive=trueendpoints.trace.enabled=true#HEALTH INDICATORS(previously health.*)management.health.db.enabled=truemanagement.health.diskspace.enabled=truemanagement.health.mongo.enabled=truemanagement.health.rabbit.enabled=truemanagement.health.redis.enabled=truemanagement.health.solr.enabled=truemanagement.health.diskspace.path=.management.health.diskspace.threshold=10485760management.health.status.order=DOWN,OUT_OF_SERVICE,UNKNOWN,UP#MVC ONLY ENDPOINTSendpoints.jolokia.path=jolokiaendpoints.jolokia.sensitive=trueendpoints.jolokia.enabled=true#when using Jolokia#JMX ENDPOINT(EndpointMBeanExportProperties)endpoints.jmx.enabled=trueendpoints.jmx.domain=#the JMX domain,defaults to'org.springboot'endpoints.jmx.unique-names=falseendpoints.jmx.static-names=#JOLOKIA(JolokiaProperties)jolokia.config.*=#See Jolokia manual#REMOTE SHELLshell.auth=simple#jaas,key,simple,springmand-refresh-interval=-1mand-path-patterns=#classpath*:/commands/**, classpath*:/crash/commands/**shell.config-path-patterns=#classpath*:/crash/*shell.disabled-commands=jpa*,jdbc*,jndi*#comma-separated list of commands to disableshell.disabled-plugins=false#don't expose pluginsshell.ssh.enabled=#ssh settings...shell.ssh.key-path=shell.ssh.port=shell.telnet.enabled=#telnet settings...shell.telnet.port=shell.auth.jaas.domain=#authentication settings...shell.auth.key.path==er.password=shell.auth.spring.roles=#GIT INFOspring.git.properties=#resource ref to generated git info properties file。