Springboot基础

1.项目依赖

1.1父项目依赖管理

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.5.3</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>

1.2导入依赖

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

2.配置相关

2.1修改配置

  • application.properties

  • application.yml

  • application.yaml

  • 配置优先级:properties > yml > yaml

2.2获取配置

@value("$(name)")
private String name;
@Resoure
private Environment env;

env.getProperty("name");
@Component
@ConfigrurationProperties(prefix = "perso")
public class Person(){
    private String name;

    getter()
    setter()
    toString()
}

2.3profile 多环境配置

  • application-dev.properties/yml
  • application-test.properties/yml
  • application-pro.properties/yml
  • 激活配置
    • 配置文件: spring.profiles.active=dev
    • 虚拟机参数:-Dspring.profiles.active=dev
    • 命令行参数:–spring.profiles.active=dev

2.4配置优先级

  • 内部

    • file:./config/: 当前项目下的/config目录下

    • file:./ : 当前项目的根目录

    • classpath:/config/ : classpath的/config目录

    • classpath:/ : classpath的根目录

  • 外部

    • jar包同级目录 /config/application.properties

    • jar包同级目录 application.properties

    • 命令行参数

2.5切换内置服务器

  • 排除tomcat
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
  • 引入jetty
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

2.6日志配置

  • 依赖
<!--Slf4j日志-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</dependency>
  • 日志级别
off > error > warning > info > debug >  all           //级别越高,输出信息越少
  • logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration  scan="true" scanPeriod="10 seconds">

    <contextName>logback</contextName>
    <!-- name的值是变量的名称,value的值时变量定义的值。定义变量后,可以使“${}”来使用变量。 -->
    <property name="logging.file.path" value="logs" />
    <property name="maxHistory" value="30" />
    <property name="maxFileSize" value="100MB" />

    <!-- 彩色日志(IDE下载插件才可以生效) -->
    <!-- 彩色日志依赖的渲染类 -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <!-- 彩色日志格式 -->
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>


    <!--输出到控制台-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>info</level>
        </filter>
        <encoder>
            <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
            <!-- 设置字符集 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- 时间滚动输出 level为 INFO 日志 -->
    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 正在记录的日志文件的路径及文件名 -->
        <!--<file>${logging.file.path}/log_info.log</file>-->
        <!--日志文件输出格式-->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天日志归档路径以及格式 -->
            <fileNamePattern>${logging.file.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!--日志文件保留天数-->
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <!-- 此日志文件只记录info级别的 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- 时间滚动输出 level为 ERROR 日志 -->
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 正在记录的日志文件的路径及文件名 -->
        <!--<file>${logging.file.path}/log_error.log</file>-->
        <!--日志文件输出格式-->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset> <!-- 此处设置字符集 -->
        </encoder>
        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logging.file.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!--日志文件保留天数-->
            <maxHistory>${maxHistory}</maxHistory>
        </rollingPolicy>
        <!-- 此日志文件只记录ERROR级别的 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <root level="info">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="INFO_FILE" />
        <appender-ref ref="ERROR_FILE" />
    </root
</configuration>

2.7 .gitignore配置

### Java template
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

### Example user template template
### Example user template

# IntelliJ project files
.idea
*.iml
out
gen

*/target
*/*.iml

3.自动配置

3.1 Condition

  • context:上下文对象,可以获取属性值,获取类加载器,获取BeanFactory等。
  • metadata:元数据对象,获取注解属性。
public class ClassCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean flag = true;
        Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClassTest.class.getName());
        System.out.println(map);
        String[] value = (String[]) map.get("value");
        try {
            for (String className : value) {
                Class<?> name = Class.forName(className);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("==========================");
            flag = false;
        }
        return flag;
    }
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ClassCondition.class)
public @interface ConditionOnClassTest {
    String[] value();
}
@Bean
@ConditionOnClassTest("redis.clients.jedis.Jedis")
public User user(){
    return new User();
}
  • springboot提供的常用条件注解
    • ConditionalOnProperty:判断配置文件中是否有对应属性和值才初始化。
    • ConditionalOnClass:判断环境中是否有对应字节码文件才初始化。
    • ConditionalOnMissingBean:判断环境中没有对应的Bean才初始化。

3.2 Import

加载外部包中的Bean

  • ComponentScan(“包路径”)
  • Import(“类.class”)

4种用法:

  • 导入Bean:@Import(User.class)
  • 导入配置类:@Import(UserConfig.class)
  • 导入ImportSelector的实现类 (@springbootApplication 依赖这个注解)
  • 导入ImportBeanDefinitionRegistrar的实现类

3.3 EnableAutoConfiguration

  • 内部使用@Import(AutoConfigurationImportSeletcor.class)来加载配置类
  • 配置文件位置:META-INFO/spring.factories 中的EnableAutoConfiguration对应的值
  • 并不是所有的Bean都会被初始化,只有满足condition条件的才会被加载。

3.4 自定义Starter

  • 创建 redis-spring-boot-autoconfigure 模块
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfigure {

    @Bean
    public Jedis jedis(RedisProperties redisProperties){
        System.out.println("!!!!!!!!!!!");
        return new Jedis(redisProperties.getHost(),redisProperties.getPort());
    }
}
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {

    private String host = "localhost";
    private int port = 6379;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
  • 创建 redis-spring-boot-starter 模块,依赖 redis-spring-boot-autoconfigure
  • 在 redis-spring-boot-autoconfigure模块中初始化jedis的Bean,并定义META-INF/spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
 com.example.redis.config.RedisAutoConfigure 
  • 在测试模块中引入redis-starter依赖,测试获取jedis的Bean,操作redis
public static void main(String[] args) {
    ConfigurableApplicationContext context = 		     SpringApplication.run(SpringBootTestApplication.class, args);

    Jedis jedis = context.getBean(Jedis.class);
    System.out.println(jedis);

    jedis.set("name","zhangsan");
}

4.监听机制

SpringBoot的监听机制,其实是对java提供的事件监听机制的封装

  • 事件 Event:继承java.util.EventObject 类的对象
  • 事件源 Source:任意对象Object。
  • 监听器 Listener:实现java.util.EventListener接口的对象。

SpringBoot中4个监听器

  • ApplicationRunner:启动时自动监听
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run");
    }
}
  • CommandLineRunner:启动时自动监听,与ApplicationRunner基本一样
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner....run");
    }
}
  • ApplicationContextInitializer:需要配置
@Component
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer.....initialize");
    }
}
  • SpringApplicationRunListener:需要配置
public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    public MySpringApplicationRunListener(SpringApplication application, String[] args) {}

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("starting.....");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("environmentPrepared.....");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("contextPrepared.....");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("contextPrepared.....");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("started.....");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("ready.....");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("failed.....");
    }
}
  • MATA-INF/spring.factories
org.springframework.context.ApplicationContextInitializer =listener.domain.MyApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener =listener.domain.MySpringApplicationRunListener

5.启动流程

5.1开始启动

  • 构建一个spring应用 new SpringApplication()
  • 初始化模块 initalize
    • 配置source
    • 配置是否为web环境
    • 创建初始化构造器
    • 创建应用监听器
    • 配置应用主方法所在类

5.2 run方法

  • 启动计时器,启动监听器
  • SpringApplicationRunListener应用启动监听模块
    • 监听:环境配置,应用上下文
  • ConfigureableEnvironment配置环境模块
    • 判断web环境
    • 加载属性文件资源
    • 配置监听
  • Springboot的Banner
  • ConfigurableApplicationContext应用上下文模块
    • 创建context
    • 基本属性配置
      • 加载配置环境
      • ResourceLoad资源加载器
      • 配置监听
      • 加载启动参数
  • refreshcontext 更新应用上下文
    • 准备环境所需的Bean工厂
    • 通过工厂模式产生所需的bean
  • 计时结束,项目启动

6.监控

  • 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 访问路径
http://localhost:8080/actuator
  • 开启配置
# 开启健康检查完整信息
management.endpoint.health.show-details=always

# 暴露所有endpoint
management.endpoints.web.exposure.include=*
  • 图形化的可以使用 springboot-admin依赖

7.四种传参方式

  • 传统方式
http://localhost:8800/demo/user/findById?id=21&name=zhangsan

public void test(Integer id,String name){}
  • 路径传参
http://localhost:8800/demo/user/findById/21/zhangsan

@GetMapping("/findById/{id}/{name}")
public void test(@PathVariable("id") Integer id,@PathVariable("name") String name){}
  • 表单传参
<form action="url">
<input type= "text" name= "zhangsan"/>

public void test(String name){}
    

<form action="url" method="post" enctype="multipart/form-data">
<input type="file" name="photo"/>
    
public void test(MultipartFile photo){}
  • json传参
异步请求(url,"{"id":21,"name":"zhangsan","age":18}")


public void test(@RequestBody User user){}

8.部署

  • jar包部署(略)

  • war包部署

<packaging>war</packaging>
@SpringBootApplication
public class SpringBootActuatorApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootActuatorApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringBootActuatorApplication.class);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值