湖南网站建设磐石网络网站开发如何报价
- 作者: 五速梦信息网
- 时间: 2026年03月21日 10:52
当前位置: 首页 > news >正文
湖南网站建设磐石网络,网站开发如何报价,花蝴蝶在线观看免费版高清,招商网站建设需要什么尚硅谷SpringBoot顶尖教程
- 全局配置文件
SpringBoot使用一个全局的配置文件 application.properties 或者 application.yml #xff0c;该配置文件放在src/main/resources目录或者类路径/config目录下面#xff0c; 可以用来修改SpringBoot自动配置的默认值。
yml是YA…尚硅谷SpringBoot顶尖教程
- 全局配置文件 SpringBoot使用一个全局的配置文件 application.properties 或者 application.yml 该配置文件放在src/main/resources目录或者类路径/config目录下面 可以用来修改SpringBoot自动配置的默认值。 yml是YAML(YAML Ain’t Markup Language)语言的文件参考规范http://www.yaml.org/ 以前的配置文件 大多都是使用xml文件 比较繁重 yml则以数据为中心 比jsonxml更适合做配置文件。
- yaml语法
2.1 基本语法
key: (空格) value 表示一对键值对儿空格必须有
以空格的缩进来控制层级关系只要是左对齐的一列数据都是同一个层级。属性和值是大小写敏感的。
server:port: 80842.2 值的写法
字面量: 普通的值数字布尔值字符串。字符串不用加单引号或者双引号。
双引号不会转义字符串里面的特殊字符特殊字符会作为本身意义表示。
name: zhangsan \n lisi
输出:
zhangsan
lisi单引号会转义特殊字符特殊字符最终只是一个普通的字符串数据。
name: zhangsan \n lisi
输出:
zhangsan \n lisi对象、Map属性和值
对象还是key: value的形式。在下一行来写对象的属性和值注意缩进。例如对象friends
friends:lastName: zhangsanage: 20对象还有行内写法
friends: {lastName: zhangsan, age: 18}数组(List、Set)
用-值表示数组中的一个元素
animals:- cat- dog- pig数组也有行内写法
animals: [cat,dog,pig]3. 配置文件值注入
3.1 ConfigurationProperties注入
配置文件配置内容如下
person:age: 18boss: falsebirth: 2017/12/12maps: {k1: v1,k2: v2}lists:- lisi- wanwudog:name: 旺财age: 2last-name: zhangsanJavaBean, 注意Person类要写setXXX()方法才会注入成功。
Component
ConfigurationProperties(prefix person) // 优先级高于value
public class Person implements Serializable {private String lastName;private Integer age;private Boolean boss;private Date birth;private MapString, Object maps;private ListObject lists;private Dog dog;// getXXX setXXX
}我们可以导入配置文件处理器以后编写配置就有提示。
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional
/dependencyyml书写效果 properties文件书写效果
测试结果 Person{lastNamezhangsan, age18, bossfalse, birthTue Dec 12 00:00:00 CST 2017, maps{k1v1, k2v2}, lists[lisi, wanwu, cat]], dogDog{name旺财, age2}}3.2 中文乱码问题 yml或properties配置文件的参数配置为中文值注入出现乱码问题。 修改系统默认配置文件的编码
3.3 Value注入 JavaBean Component public class Person implements Serializable {Value(\({person.last-name})private String lastName;Value(#{10*2})private Integer age;Value(true)private Boolean boss;private Date birth;// Value不支持复杂类型 // Value(\){person.maps})private MapString, Object maps;private ListObject lists;private Dog dog;// getXXX setXXX }测试结果 Person{lastNamezhangsan, age20, bosstrue, birthnull, mapsnull, listsnull, dognull}ConfigurationProperties优先级高于Value 3.4 ConfigurationProperties结合PropertySource 如果不想将person属性配置在全局配置文件(properties或yaml)中 可以放到自定义的properties文件中。 自定义person.properties文件 person.last-name张胜男\({random.uuid} person.age\){random.int} person.birth2017/12/15 person.bossfalse person.maps.k1v1 person.maps.k2v2 person.lists[pig,dog,cat] person.dog.name旺财-\({person.last-name}-\){person.hello:hello} person.dog.age2在JavaBean类上使用PropertySource引入自定义的properties文件。 Component PropertySource(value {classpath:person.properties}) ConfigurationProperties(prefix person) // 优先级高于value public class Person implements Serializable {private String lastName;private Integer age;private Boolean boss;private Date birth;private MapString, Object maps;private ListObject lists;private Dog dog;// getXXX setXXX }测试结果 Person{lastName张胜男6eea5415-7d81-41a1-95be-bf72dba5b839, age-298203675, bossfalse, birthFri Dec 15 00:00:00 CST 2017, maps{k1v1, k2v2}, lists[[pig, dog, cat]], dogDog{name旺财-张胜男c650e5a0-791f-4f39-9d4f-1bea2d7527bf-hello, age2}}3.5 ConfigurationProperties结合Bean ConfigurationProperties结合Bean可以为属性赋值 。 JavaBean public class Dog {private String name;private Integer age;// getXXX , setXXX } 在全局配置文件yaml中配置dog对象的属性值。 dog:name: 旺财age: 2在主启动类或配置类中使用 ConfigurationProperties结合Bean声明dog实例并给属性赋值。 Bean ConfigurationProperties(prefix dog) public Dog dog() {return new Dog(); }测试结果 Dog{name旺财, age2}3.6 JSR303校验 ConfigurationProperties结合Validated注解支持JSR303进行配置文件属性值的校验。 pom.xml文件中需要加入相关依赖尤其是验证依赖的实现类。 dependencygroupIdjavax.validation/groupIdartifactIdvalidation-api/artifactId /dependency dependencygroupIdorg.hibernate/groupIdartifactIdhibernate-validator/artifactIdversion5.2.4.Final/version /dependencyJavaBean package com.atgugui.bean; import org.springframework.validation.annotation.Validated; // ….省略导入 Component ConfigurationProperties(prefix person) // 优先级高于value Validated public class Person implements Serializable {Null // lastName必须为空private String lastName;private Integer age;private Boolean boss;private Date birth;private MapString, Object maps;private ListObject lists;private Dog dog;// getXXX setXXX }启动应用报错测试结果 Property: person.lastNameValue: 张胜男562391e3-b84a-4d4d-ad9e-3d0322d67e94Reason: 必须为null3.7 Value和 ConfigurationProperties比较 功能批量注入配置文件中的属性一个个指定松散绑定松散语法支持不支持SpEL不支持支持JSR303数据校验支持不支持复杂类型封装支持不支持如果我们只是在某个业务逻辑中需要获取一下配置文件中的某项值就用Value 4. ImportResource 读取外部配置文件导入Spring的配置文件让配置文件里面的内容生效。在对SSM老项目进行架构升级时可以在配置类中使用该注解将原来xml配置中的Bean维护到IOC容器中实现与SpringBoot兼容的效果。 编写xml配置 beans.xml ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdbean idhelloServiceBean classcom.atgugui.service.HelloServiceBean/ /beans编写test测试模拟 SpringBootTest RunWith(SpringRunner.class) class SpringBoot01HelloQuickApplicationTests {AutowiredApplicationContext ioc;Testpublic void testHelloService() {boolean helloServiceBean ioc.containsBean(helloServiceBean);System.out.println(MessageFormat.format(contains helloServiceBean: {0}, helloServiceBean));} }没使用ImportResouce注解的测试结果 contains helloServiceBean: falseSpringBoot里面没有Spring的xml配置文件我们自己编写的xml配置文件也不能自动识别。想让Spring的xml配置文件加载生效使用ImportResource注解。可以在主启动类添加 ImportResource注解指定要加载的xml配置。 SpringBootApplication ImportResource(locations {classpath:beans.xml}) public class SpringBoot01HelloQuickApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot01HelloQuickApplication.class, args);} }使用ImportResouce注解的测试结果 contains helloServiceBean: true当然SpringBoot推荐使用JavaConfig配置类的方式给容器中添加组件不编写xml配置。 不需要编写xml配置改用配置类实现Spring配置文件 Configuration public class MyAppConfig {// 将方法的返回值添加到容器中容器中这个组件默认的id就是方法名Beanpublic HelloServiceBean helloServiceBean() {System.out.println(配置类Bean给容器中添加HelloServiceBean组件);return new HelloServiceBean();} }测试结果 配置类Bean给容器中添加HelloServiceBean组件 contains helloServiceBean: true5. 配置文件占位符 5.1 随机数 RandomValuePropertySource 配置文件中可以使用随机数。
5.2 属性配置占位符 可以在配置文件中引用前面配置过的属性。\({person.hello:默认值} 来指定找不到属性时的默认值。 编写占位符配置 person.last-name张胜男\){random.uuid} person.age\({random.int} person.dog.name旺财-\){person.last-name}-\({person.hello:hello}打印person测试结果 Person{lastName张胜男80eae444-2550-442c-b657-f5f6704794a3, age1952295864, bossfalse, birthFri Dec 15 00:00:00 CST 2017, maps{k1v1, k2v2}, lists[[pig, dog, cat]], // 读取到上面的person.last-name \){person.hello}没有就使用指定的默认值hello dogDog{name旺财-张胜男91918168-7841-41ce-9359-7129d6a866cd-hello, age2}}6. Profile 6.1 多profile文件形式 格式application-{profile}.properties application-dev.properties application-prod.properties 然后在默认配置文件application.properties中指定加载哪个环境的配置文件: #指定加载dev环境配置 spring.profiles.activedev #指定加载prod环境配置 #spring.profiles.activeprod6.2 yml支持多profile文档块形式 使用三个短横线分割多个profile文档块然后通过spring.profiles.active${profile}指定加载哪个环境的配置。 spring:profiles:active: prod — server:port: 8081 spring:profiles: dev— server:port: 8084 spring:profiles: prod6.3 profile激活方式 可以在全局配置文件中指定 spring.profiles.activedev
也可以在在命令行指定 –spring.profiles.activedev 如果执行jar包也可以指定环境配置 java -jar xxx.jar –spring.profiles.activedev
jvm参数指定配置环境 -Dspring.profiles.activedev
系统环境变量也可以指定
- 配置文件加载位置
Spring Boot启动会扫描以下位置的application.properties或者application.yml文件作为SpringBoot的默认配置文件。 file:./config/ file:./ classpath:/config/ classpath:/
以上都是按照优先级从高到低的顺序所有位置的文件都会被加载高优先级配置内容会覆盖低优先级配置内容。SpringBoot会从这四个位置全部加载主配置文件互补配置。我们也可以通过配置spring.config.location来改变默认配置。 java -jar xxx.jar –spring.config.locationD:\application.properties8. 外部配置加载顺序 SpringBoot支持多种外部配置方式可以从以下位置加载配置。优先级从高到低高优先级的配置会覆盖低优先级的配置所有的配置会形成互补配置。 命令行参数, 多个参数配置用空格分开 java -jar xxx.jar –server.port8082 –server.context-path/abc来自java:comp/env的JNDI属性Java系统属性(System.getProperties())操作系统环境变量 由jar包外向jar包内寻找优先加载带profile的配置 jar包外部的application-{profile}.properties或application-{profile}.yml(带spring.profile)配置文件。 jar包内部的application-{profile}.properties或application-{profile}.yml(带spring.profile)配置文件。 jar包外部的application-{profile}.properties或application-{profile}.yml(不带spring.profile)配置文件。 jar包内部的application-{profile}.properties或application-{profile}.yml(不带spring.profile)配置文件。 Configuration注解类上的PropertySource 通过SpringApplication.setDefaultProperties指定的默认属性。 参考官方资料: https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#boot-features-external-config
- 自动配置原理
9.1 剖析源码 SpringBoot启动的时候加载主配置类开启了自动配置功能 EnableAutoConfiguration EnableAutoConfiguration作用 利用AutoConfigurationImportSelector给容器导入一些组件。 可以导入selectImport()方法的内容通过下面的方法获取候选的配置。 AutoConfigurationImportSelector#selectImports Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return NO_IMPORTS;}try {// …// 获取候选的配置ListString configurations getCandidateConfigurations(annotationMetadata,attributes);// ….}catch (IOException ex) {throw new IllegalStateException(ex);}}AutoConfigurationImportSelector#getCandidateConfigurations protected ListString getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {// SpringFactoriesLoader加载META-INF/spring.factories文件配置ListString configurations SpringFactoriesLoader.loadFactoryNames(// getSpringFactoriesLoaderFactoryClass()EnableAutoConfiguration.classgetSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());Assert.notEmpty(configurations,No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.);return configurations;
}AutoConfigurationImportSelector#getSpringFactoriesLoaderFactoryClass protected Class? getSpringFactoriesLoaderFactoryClass() {return EnableAutoConfiguration.class;
}SpringFactoriesLoader#loadFactoryNames(…) 扫描所有jar包类路径下META-INF/spring.factories把扫描到的这些文件内容包装成Properties对象。 从properties中获取EnableAutoConfiguration.class类对应的值然后把它们加载到容器中。 将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration.class类对应的值加入到容器中。 public static ListString loadFactoryNames(Class? factoryClass, ClassLoader classLoader) {// EnableAutoConfiguration.class.getName()EnableAutoConfigurationString factoryClassName factoryClass.getName();try {// FACTORIES_RESOURCE_LOCATION META-INF/spring.factoriesEnumerationURL urls (classLoader ! null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));// 存放解析后的候选配置ListString result new ArrayListString();while (urls.hasMoreElements()) {URL url urls.nextElement();// 将解析的组件封装到properties对象中Properties properties PropertiesLoaderUtils.loadProperties(new UrlResource(url));String factoryClassNames properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}return result;}catch (IOException ex) {throw new IllegalArgumentException(Unable to load [ factoryClass.getName() ] factories from location [ FACTORIES_RESOURCE_LOCATION ], ex);}}下图中每一个这样的xxxAutoConfiguration类都是容器中的一个组件都加入到容器中进行自动配置。
9.2 案例分析 以HttpEncodingAutoConfiguration为例解释自动配置原理 // 表示这是一个配置类相当于以前的xml配置 Configuration // 启动指定配置类的属性配置绑定 EnableConfigurationProperties(HttpEncodingProperties.class) // Spring底层Conditional注解根据不同的条件 以及是否满足指定的条件来控制整个配置类里面的配置是否生效 ConditionalOnWebApplication // 判断当前应用是否是web应用 如果是web应用则生效 // 判断当前项目有没有指定的类 如果有则生效 ConditionalOnClass(CharacterEncodingFilter.class) // SpringMVC中解决乱码问题的过滤器 // 判断配置文件中是否存在某个配置属性matchIfMissingtrue 如果判断不存在默认也成立并生效 ConditionalOnProperty(prefix spring.http.encoding, value enabled, matchIfMissing true) public class HttpEncodingAutoConfiguration {// 与SpringBoot项目的全局配置文件application.properties建立映射关系private final HttpEncodingProperties properties;// 只有一个有参构造器时 参数的属性值就会从容器中获取public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {this.properties properties;}Bean// 给容器中添加一个组件该组件的某些属性值要从this.properties中获取ConditionalOnMissingBean(CharacterEncodingFilter.class)public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));return filter;}// …. }以上根据当前不同的条件判断决定这个配置类是否生效。一旦这个配置类生效这个配置类就会给容器中添加各种组件这些组件的属性从对应的properties类中获取的这些类里面的每一个属性又是和配置文件绑定的。 所有在配置文件中能配置的属性是在xxxProperties类中封装着配置文件能配置什么就可以参照某个功能对应的这个属性类。 #我们能配置的属性都是来源于这个功能的properties类 spring.http.encoding.enabledtrue spring.http.encoding.charsetutf-8 spring.http.encoding.forcetrue将SpringBoot项目全局配置文件中spring.http.encoding前缀的属性值绑定并填充到HttpEncodingProperties中. 实现属性值的绑定读取需要在启动类或配置类上添加EnableConfigurationProperties注解开启属性绑定配置。 ConfigurationProperties(prefix spring.http.encoding) public class HttpEncodingProperties {//… }9.3 Conditional派生注解 Conditional派生注解(Spring注解版原生的Conditional作用) 必须是Conditional指定的条件成立才给容器中添加组件配置里面的所有内容才会生效。 Conditional扩展注解作用判断是否满足当前指定条件ConditionalOnJava系统的java版本是否符合要求ConditionalOnBean容器中存在指定BeanConditionalOnMissingBean容器中不存在指定BeanConditionalOnExpression满足SpEL表达式指定ConditionalOnClass系统中有指定的类ConditionalOnMissingClass系统中没有指定的类ConditionalOnSingleCandidate容器中只有一个指定的Bean或者这个Bean是首选BeanConditionalOnProperty系统中指定的属性是否有指定的值ConditionalOnResource类路径下是否存在指定资源文件ConditionalOnWebApplication当前是web环境ConditionalOnNotWebApplication当前不是web环境ConditionalOnJndiJNDI存在指定项 自动配置类必须在一定的条件下才能生效。我们如何知道哪些自动配置类生效。可以通过在全局配置文件application.properties文件中配置SpringBoot的debug模式来让控制台打印自动配置报告从而查看哪些自动配置类生效。 #开启SpringBoot的debug模式 debugtrue查看SpringBoot项目启动日志 匹配上且生效的自动配置类 Positive matches: —————–DispatcherServletAutoConfiguration matched:- ConditionalOnClass found required class org.springframework.web.servlet.DispatcherServlet; ConditionalOnMissingClass did not find unwanted class (OnClassCondition)- ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:- ConditionalOnClass found required class javax.servlet.ServletRegistration; ConditionalOnMissingClass did not find unwanted class (OnClassCondition)- Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)// ……..没有生效的自动配置类 Negative matches: —————–ActiveMQAutoConfiguration:Did not match:- ConditionalOnClass did not find required classes javax.jms.ConnectionFactory, org.apache.activemq.ActiveMQConnectionFactory (OnClassCondition)AopAutoConfiguration:Did not match:- ConditionalOnClass did not find required classes org.aspectj.lang.annotation.Aspect, org.aspectj.lang.reflect.Advice (OnClassCondition)// …………..
2023-03-12 20:45:19.142 INFO 21220 — [ main] c.a.SpringBoot01HelloQuickApplication : Started SpringBoot01HelloQuickApplication in 2.672 seconds (JVM running for 4.087)
相关文章
-
湖南网站建设公司磐石网络网站备案必须做前置审批吗
湖南网站建设公司磐石网络网站备案必须做前置审批吗
- 技术栈
- 2026年03月21日
-
湖南网站建设费用十大国外室内设计网站
湖南网站建设费用十大国外室内设计网站
- 技术栈
- 2026年03月21日
-
湖南网站建设seo优化html代码大全表格
湖南网站建设seo优化html代码大全表格
- 技术栈
- 2026年03月21日
-
湖南网站建设营销推广十大免费行情软件下载网站
湖南网站建设营销推广十大免费行情软件下载网站
- 技术栈
- 2026年03月21日
-
湖南网站设计外包哪家好苏州网站建设公司鹅鹅鹅
湖南网站设计外包哪家好苏州网站建设公司鹅鹅鹅
- 技术栈
- 2026年03月21日
-
湖南网站推广优化php网站开发代做
湖南网站推广优化php网站开发代做
- 技术栈
- 2026年03月21日
