-
获取配置文件中的信息
- 批量注入
- 创建实体类Person
//将当前类加入到spring容器 @Component //配置当前类要读取的配置文件的,前缀是什么 @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boos; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; }
- 新建application.yml文件,并且加入对应的配置信息
#这个前缀和person类中配置的前缀必须一致 person: lastName: 张三 age: 18 boos: false birth: 1998-04-12 # 映射map maps: {k1: v2,k2: v2} # 映射list lists: - 李四 - 王五 # 映射一个对象 dog: name: 小狗 age: 30
- 为了在yml中修改信息时有提示可以在pom中新加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>2.1.7.RELEASE</version> </dependency>
- 单个注入
- 使用@value注解
@Component public class Dog { @Value("${person.dog.name}") private String name; @Value("#{11*2}") private Integer age; }
其中${}是获取配置文件中的值,#{}是可以写表达式
-
注意:
- @ConfigurationProperties:支持复杂数据类型注入
- @Value:不支持复杂类型数据注入
- 批量注入
-
@PropertySource
- 加载指定配置文件
- 在resource目录下新建custom.properties配置文件
jdbc.name = root jdbc.pwd = 123456 jdbc.url = jdbc:mysql//localhost:3306/user
- 新建JdbcConfig类
@Component //指定加载custom.properties的配置信息 @PropertySource(value = {"classpath:custom.properties"}) //加载以jdbc开头的配置信息 @ConfigurationProperties(prefix = "jdbc") public class JdbcConfig { private String name; private String pwd; private String url; }
-
@ImportResource
- 导入spring的配置文件,使其生效
- 一般也没有使用,springboot推荐使用@Configuration和@Bean注解
-
@Configuration和@Bean
- @Configuration注解声明当前类时一个配置类
- @Bean注解将当前方法的返回值添加到ioc容器中,实例的id就是方法名
@Configuration public class MyAppConfig { // @Bean注解,将方法的返回值添加到ioc容器中,组件的默认id就是方法名 @Bean public HelloService helloService(){ return new HelloService(); } }
-
spring.profiles
用于指定当前处于那个环境,也可以使用新建文件application-环境名称.properties spring.profiles= 环境名称
-
spring.profiles.active
用于指定当前运行使用的是哪一个配置信息 spring.profiles=dev
-
多配置文件
- 如果使用的yml配置文件,除了上面的方法还可以使用单个文件,多文档的方式
#设置当前运行环境属于哪个配置环境 spring: profiles: active: dev #这个前缀和person类中配置的前缀必须一致 person: lastName: 张三 age: 18 boos: false birth: 1998/04/12 # 映射map maps: {k1: v2,k2: v2} # 映射list lists: - 李四 - 王五 # 映射一个对象 dog: name: 小狗 age: 30 #---可以将一个配置文件分成多个文档块 --- server: port: 8080 spring: profiles: dev --- server: port: 8081 spring: profiles: prod
-
springboot文件的加载位置
- 会依次扫描以下位置
项目根目录下的:/config/application.yml 项目根目录下的:/application.yml classpath下的:classpath:/config/application.yml classpath下的:classpath:/application.yml
- 依次扫描,已配置的项按照优先级高的来,互补配置
- 可以使用命令行参数的形式,--spring.config.location来指定配置文件的位置,与其他配置文件也是互补配置
java -jar test.jar --spring.config.location=G:/application.yml
-
自动配置@EnableAutoConfig
- 依赖spring-boot-autoconfigure中的MATA-INF/spring.factories中展示了需要加载哪些自动配置类
- 查询选择一个全类名查找出该类,例如:org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
- 搜索出当前类,信息如下
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(HttpProperties.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(CharacterEncodingFilter.class) @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) public class HttpEncodingAutoConfiguration { private final HttpProperties.Encoding properties; public HttpEncodingAutoConfiguration(HttpProperties properties) { this.properties = properties.getEncoding(); } @Bean @ConditionalOnMissingBean 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; } @Bean public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() { return new LocaleCharsetMappingsCustomizer(this.properties); } private static class LocaleCharsetMappingsCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered { private final HttpProperties.Encoding properties; LocaleCharsetMappingsCustomizer(HttpProperties.Encoding properties) { this.properties = properties; } @Override public void customize(ConfigurableServletWebServerFactory factory) { if (this.properties.getMapping() != null) { factory.setLocaleCharsetMappings(this.properties.getMapping()); } } @Override public int getOrder() { return 0; } } }
- 其中@EnableConfigurationProperties(HttpProperties.class)注解中的类就是可以在springBoot配置文件中配置的信息
@ConfigurationProperties(prefix = "spring.http") public class HttpProperties { /** * Whether logging of (potentially sensitive) request details at DEBUG and TRACE level * is allowed. */ private boolean logRequestDetails; /** * HTTP encoding properties. */ private final Encoding encoding = new Encoding(); public boolean isLogRequestDetails() { return this.logRequestDetails; } public void setLogRequestDetails(boolean logRequestDetails) { this.logRequestDetails = logRequestDetails; } public Encoding getEncoding() { return this.encoding; } /** * Configuration properties for http encoding. */ public static class Encoding { public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; /** * Charset of HTTP requests and responses. Added to the "Content-Type" header if * not set explicitly. */ private Charset charset = DEFAULT_CHARSET; /** * Whether to force the encoding to the configured charset on HTTP requests and * responses. */ private Boolean force; /** * Whether to force the encoding to the configured charset on HTTP requests. * Defaults to true when "force" has not been specified. */ private Boolean forceRequest; /** * Whether to force the encoding to the configured charset on HTTP responses. */ private Boolean forceResponse; /** * Locale in which to encode mapping. */ private Map<Locale, Charset> mapping; public Charset getCharset() { return this.charset; } public void setCharset(Charset charset) { this.charset = charset; } public boolean isForce() { return Boolean.TRUE.equals(this.force); } public void setForce(boolean force) { this.force = force; } public boolean isForceRequest() { return Boolean.TRUE.equals(this.forceRequest); } public void setForceRequest(boolean forceRequest) { this.forceRequest = forceRequest; } public boolean isForceResponse() { return Boolean.TRUE.equals(this.forceResponse); } public void setForceResponse(boolean forceResponse) { this.forceResponse = forceResponse; } public Map<Locale, Charset> getMapping() { return this.mapping; } public void setMapping(Map<Locale, Charset> mapping) { this.mapping = mapping; } public boolean shouldForce(Type type) { Boolean force = (type != Type.REQUEST) ? this.forceResponse : this.forceRequest; if (force == null) { force = this.force; } if (force == null) { force = (type == Type.REQUEST); } return force; } public enum Type { REQUEST, RESPONSE } } }
例如当前类,就可以配置spring.http.encoding.charset等等
-
开启debug模式
- 在配置文件中配置debug=true可以查看哪些自动配置文件被加载了
============================ CONDITIONS EVALUATION REPORT ============================ // 已匹配上的自动配置类 Positive matches: ----------------- AopAutoConfiguration matched: - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition) // 未匹配上的自动配置类 Negative matches: ----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)
-
日志
- springBoot底层使用sl4j+logback来进行日志记录
- springboot也导入了中间替换包(偷梁换柱包),解决一些别人写好的框架的日志依赖不是sl4j+logback组合的问题
- 日志级别 trace<debug<info<warn<error 可以根据级别控制是否打印对应日志
- springboot默认的日志级别是info级别,意思是info以下的级别日志不会打印
- springboot调整日志级别,在配置文件中写logging.level.指定包名=debug
logging.level.com.study.springboot = debug
- logging.file和logging.path
logging.file:指定生成的日志文件的名称 logging.path:指定日志文件生成的路径
- logging.pattern.file:指定输出到文件中的日志的格式
- springboot默认的日志配置信息在:springboot依赖->org.springframework.boot->logging->logback->defaults.xml文件中
网友评论