【Spring】springboot 学习笔记2

目录

一、配置文件

1.1 配置文件读取方式

1.1.1  使用@ConfigurationProperties获取配置文件内容

1.1.2 使用 @PropertySource(value = {"classpath: person.properties"})读取指定配置文件内容

1.1.3 使用 @Value 读取指定内容

1.1.4 使用 @ImportResource 导入 spring 的配置文件

1.2 与 @Value 对比

1.3 SpringBoot 推荐的配置类配置方式

1.4 多环境支持

1.4.1 properties 文件

1.4.2 yml 文件

1.4.3 使用 idea 配置直接指定

1.4.4 指定默认启动文件的路径(重要)

1.4.5 配置文件加载位置优先级

1.4.6 配置项目的访问路径

1.5 自动配置原理

二、日志框架


一、配置文件

1.1 配置文件读取方式

1.1.1  使用@ConfigurationProperties获取配置文件内容

@ConfigurationProperties(prefix = "person") 代表配置文件中前缀内的数据内容
由于必须是组件这个 @ConfigurationProperties 才会生效,故要加上 @Component

@Component
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {

 

1.1.2 使用 @PropertySource(value = {"classpath: person.properties"})读取指定配置文件内容

@PropertySource 需要和 @ConfigurationProperties 配合使用

@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person implements Serializable {
。。。。
}

1.1.3 使用 @Value 读取指定内容

只需要把当前实体类加入到容器中,即可以用 SpEL 表达式获取 application.properties 中的参数

@Component
public class Person implements Serializable {

    private static final long serivalVersionUID = 1L;

    @Value("${person.last-name}")
    private String lastName;

    ... 
}

1.1.4 使用 @ImportResource 导入 spring 的配置文件

 

1.2 与 @Value 对比

 @ConfigurationProperties@Value
功能批量注入配置文件中的属性一个个指定
松散绑定(松散语法)支持不支持
SpEL不支持支持
JSR303数据校验支持不支持
复杂类型封装支持不支持,只能取出基本类型数据
使用场景专门写了一个 javaBean 来和配置文件进行映射时使用只在某个业务逻辑中需要获取一个配置文件中的某项值,使用 @Value

 

1.3 SpringBoot 推荐的配置类配置方式

SpringBoot 推荐使用 @Configuration 注解,实现全注解配置配置文件

config/MyAppConfig

/**
 * 指明当前类是一个配置类,用来替代之前的spring配置文件
 */
@Configuration
public class MyAppConfig {

    private String url;

    /**
     * 将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
     * @return
     */
    @Bean
    public HelloService helloService() {
        System.out.println("配置类中@Bean添加组件了");

        url = "http://www.baidu.com";
        return new HelloService();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

运行时,发现自动添加到容器中了

测试用例:

@Test
public void testHelloService() {
    System.out.println(myAppConfig.getUrl());
}

  

 

1.4 多环境支持

1.4.1 properties 文件

选择 properties 文件做配置文件时,只需要使用 spring.profiles.active 指定当前的配置文件

如创建文件 application-dev.properties,application-prod.properties

  

// 主配置文件 application.properties 中

spring.profiles.active=prod

1.4.2 yml 文件

与 properties 文件不同,yml 文件的配置是在 application.yml 文件中,通过 --- 分块符区分模块,并用 spring.profiles.active 指定当前的配置文件

server:
  port:8081
spring:
  profiles:
    active: prod
---
server:
  port: 8086
spring:
  profiles: dev
person:
  lastName: 小张
  age: 18
  maps: {k1:v1, k2:v2}
---

server:
  port: 8087
spring:
  profiles: prod
person:
  lastName: 小张333
  age: 18
  maps: {k1:v1, k2:v2}

1.4.3 使用 idea 配置直接指定

 

1.4.4 指定默认启动文件的路径(重要)

springboot 中可以通过 spring.config.location 指定默认的配置文件路径。可以在部署到服务器时,指定在 war 包外部存放的配置文件,实现只修改配置文件,不修改项目代码。

nohup java  -jar ${CRTDIR}/imapi-socket-2.0.war --spring.config.location=${C
RTDIR}/application-local.properties,${CRTDIR}/application.properties --logging.config=${CRTDIR}/logback-spring.xml > /dev/null 2>&1 &

 

1.4.5 配置文件加载位置优先级

默认加载位置的顺序:

  • -- file:./config/
  • -- file:./
  • -- classpath:/config/
  • -- classpath:/

特性:

  • 优先级从高到底的顺序,所有位置的文件都会被加载,可以实现互补配置
  • 高优先级会覆盖低优先级配置的内容

 

1.4.6 配置项目的访问路径

使用 server.context-path 可以指定项目的访问路径

server.context-path = /boot

 

1.5 自动配置原理

 

二、日志框架

2.1 常见日志框架和选择

日志抽象框架:

  • JCL
  • SLF4j:与 Log4j 和 Logback 同源
  • jboss-logging

日志实现框架:

  • Log4j:存在性能问题
  • JUL
  • Log4j2:apache公司出品,但与其他框架的兼容性不足
  • Logback

最终选择:

抽象框架: SLF4j      实现框架: Logback

 

2.2 SLF4j 的使用

2.2.1 如何让系统中所有的日志都统一到 slf4j

  • 将系统中其他的日志系统都排除出去(去掉依赖)
  • 用中间包替换原有的日志框架
  • 导入slf4j其他的实现

 

2.2.2 日志输出格式

格式:

  • %d: 表示日期时间
  • %thread: 表示线程名
  • %-5level: 级别从左显示5个字符宽度
  • %logger{50}:表示 logger 名字最长50个字符,否则按照句点分割
  • %msg: 日志消息
  • %n:换行符

例子:

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} === [%thread] === %-5level === %logger{50} === %msg%n

  

 

2.2.3 自定义日志配置文件

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
<!--    <property name="LOG_PATH" value="d:/logs"/>-->
    <!--设置系统日志目录-->
    <property name="APPDIR" value="app"/>

    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- 日志记录器,日期滚动记录 -->
    <appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/api.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/info/api-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>50MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!-- 追加方式记录日志 -->
        <append>true</append>
        <!-- 日志文件的格式 -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} - %logger{50} %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!-- 此日志文件只记录info级别以上的 -->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>

    <logger name="org.springframework.aop.aspectj" level="ERROR"/>
    <logger name="org.mongodb" level="ERROR"/>
    <logger name="io.netty" level="ERROR"/>
    <logger name="org.redisson" level="ERROR"/>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="org.tio.client.TioClient" level="ERROR"/>
    <!-- <root level="DEBUG"> -->
    <root level="INFO">
        <appender-ref ref="FILEINFO"/>
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

 

三、SpringBoot 结合 web 项目

3.1 静态资源映射

3.1.1 默认映射路径

"classpath":"/META-INF/resources/",
"classpath":"/resources/",
"classpath":"/static/",
"classpath":"/public/",
"/":当前项目的根路径

浏览器默认图标路径:

resources/resources/favicon.icon

 

3.1.2 自定义静态资源映射路径

在 application.properties 配置文件中,配置:

spring.resources.static-locations=classpath:/hello,classpath:/data/

 

3.2 模板引擎

3.2.1 引入 Thymeleaf

<properties>
    ...
    <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>3.0.11</thymeleaf-layout-dialect.version>
</properties>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.2.2 Thymeleaf 语法

th:任意html属性;来替换原生属性的值,如:th:text;改变当前元素里面的文本内容;th:id th:class 等

Simple expressions:(表达式语法)     Variable Expressions: ${...}:获取变量值;OGNL;      1)、获取对象的属性、调用方法               2)、使用内置的基本对象:               #ctx : the context object.                   #vars: the context variables.
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5
     #vars: the context variables.                              #locale : the context locale.                 #request : (only in Web Contexts) the HttpServletRequest object.                 #response : (only in Web Contexts) the HttpServletResponse object.                 #session : (only in Web Contexts) the HttpSession object.                 #servletContext : (only in Web Contexts) the ServletContext object.                                  ${session.foo}             3)、内置的一些工具对象: #execInfo : information about the template being processed. #messages : methods for obtaining externalized messages inside variables expressions, in the  same way as they would be obtained using #{…} syntax. #uris : methods for escaping parts of URLs/URIs #conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections. #ids : methods for dealing with id attributes that might be repeated (for example, as a  result of an iteration).       Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;      补充:配合 th:object="${session.user}:         <div th:object="${session.user}">     <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>     <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>     <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>     </div>          Message Expressions: #{...}:获取国际化内容     Link URL Expressions: @{...}:定义URL;      @{/order/process(execId=${execId},execType='FAST')}              Fragment Expressions: ~{...}:片段引用表达式      <div th:insert="~{commons :: main}">...</div>                       Literals(字面量)       Text literals: 'one text' , 'Another one!' ,…       Number literals: 0 , 34 , 3.0 , 12.3 ,…       Boolean literals: true , false       Null literal: null       Literal tokens: one , sometext , main ,… Text operations:(文本操作)     String concatenation: +     Literal substitutions: |The name is ${name}| Arithmetic operations:(数学运算)
    Binary operators: + , ‐ , * , / , %

 

3.2.3 使用

 

三、SpringBoot 数据库

3.1 使用 Druid 实现数据库操作

 

3.1.1 默认映射路径

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以和你分享一些关于Spring Boot的学习笔记。 1. Spring Boot是什么? Spring Boot是一个基于Spring框架的快速开发框架,它能够帮助开发者快速搭建Spring项目,简化了Spring应用开发的繁琐过程,提高了开发效率。 2. Spring Boot的优点有哪些? Spring Boot的优点有很多,其中包括: - 简化了Spring应用的开发,提高了开发效率; - 集成了很多常用的第三方库,减少了依赖管理的工作; - 自动化配置,减少了配置文件的编写工作; - 内嵌了Tomcat等Web容器,使得应用的部署更加便捷; - 提供了Actuator等模块,使得应用的监控和管理更加便捷。 3. Spring Boot的核心注解有哪些? Spring Boot的核心注解包括: - @SpringBootApplication:标注在启动类上,代表这是一个Spring Boot应用; - @Controller:标注在控制器类上,处理HTTP请求; - @Service:标注在服务类上,用于处理业务逻辑; - @Repository:标注在数据访问类上,用于数据库访问; - @Configuration:标注在配置类上,用于配置Spring应用上下文。 4. Spring Boot的配置文件有哪些? Spring Boot的配置文件包括: - application.properties:基于Key-Value的属性文件; - application.yml:基于YAML语法的配置文件。 5. 如何使用Spring Boot集成数据库? 使用Spring Boot集成数据库需要完成以下几个步骤: - 在pom.xml中添加相关数据库依赖; - 配置数据源和JPA/Hibernate等相关配置; - 编写实体类和DAO层代码。 以上就是一些关于Spring Boot的学习笔记,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值