zoukankan      html  css  js  c++  java
  • SpringBoot

    SpringBoot

    javase:OOP

    mysql:持久化

    html+css+jquery+框架:视图

    java:独立开发 MVC 三层架构网站:原始

    ssm:框架:简化我们开发流程,配置也开始较为复杂

    war:tomcat 运行

    spring 再简化:SpringBoot-jar:内嵌 tomcat;微服务架构

    服务越来越多:SpringCould

    SpringBoot 快速入门

    什么是 spring?

    Spring 是为了解决企业级应用开发的复杂性而创建的,简化开发

    spring 如何简化 Java 开发?

    • 4 个策略:
    1. 基于 pojo 的轻量级和最小入侵编程
    2. 通过 IOC,依赖注入,和面向接口解耦合
    3. 基于切面(AOP)进行声明式编程
    4. 通过切面和模板(Template)减少样式代码

    什么是 SpringBoot?

    Spring Boot 是一个框架,一种全新的编程规范,他的产生简化了框架的使用,所谓简 化是指简化了 Spring 众多框架中所需的大量且繁琐的配置文件,所以 Spring Boot 是一个服 务于框架的框架,服务范围是简化配置文件。所以从本质上来说,Spring Boot 其实就是 Spring 框架的另一种表现形式。约定大于配置

    SpringBoot优点:

    • 简化开发,配置简单
    • 内嵌式 web 项目
    • 没有冗余代码生成和 xml 配置

    springboot 原理

    pom.xml

    • spring-boot-dependencies:核心依赖在父工程
    • 我们在写或引入依赖时,不需要指定版本,因为这些版本

    启动器

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    • 启动器:就是 springboot 的启动场景
    • 比如spring-boot-starter-web,他就会帮我们自动导入 web 环境所需要的依赖
    • springboot 会将所有功能场景,变成启动器
    • 我们使用什么功能,找到对应启动器就可

    主程序

    //@SpringBootApplication:标注这个类是一个 springboot的应用,启动类下所有资源被导入
    @SpringBootApplication
    public class Springbootdemo01Application {
    
        //将 springboot 应用启动
        public static void main(String[] args) {
            SpringApplication.run(Springbootdemo01Application.class, args);
        }
    }
    

    注解

    @SpringBootConfiguration  springboot 配置
    	@Configuration   spring 配置
    			@Component	 说明这也是一个 spring 注解
    			
    @EnableAutoConfiguration   自动配置
      @AutoConfigurationPackage   自动配置包
      		@Import({Registrar.class})   导入选择器:注册
      @Import(AutoConfigurationImportSelector.class)
      		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);//获取所有配置
    

    获取候选配置(核心方法)

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
       List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
             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;
    }
    
    自动配置核心文件:spring-boot-autoconfigure-2.3.7.RELEASE.jar/META-INF/spring.factories  
    

    结论:springboot 所有的自动配置都是在启动时扫描并加载'spring.factories',所有的自动配置类都在里面,但是不一定生效,要判断条件是否成了,只要导入对应 start,就有对应启动器,有了启动器,就会自动装配,然后配置就成功了。

    1. springboot启动的时候从类路径下/META/INF/spring.factories 获取制定的值
    2. 将这些自动配置类导入容器,自动配置就会生效,帮我们进行配置
    3. 以前我们需要自动配置的东西,现在 springboot 帮我们做了
    4. 整个 javaEE,解决方案和自动配置的东西都在spring-boot-autoconfigure-2.3.7.RELEASE.jar这个包下
    5. 他会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器中
    6. 容器中也会存在非常多的 xxxAutoConfiguration 的文件(@Bean),就是这些类给容器中导入了整个场景需要的所有组件;并自动配置。
    7. 有了自动配置类,免去我们手动编写配置文件工作

    启动类中SpringApplication所作的事情

    1. 推断应用类型是否为 WEB
    2. 加载所有可用初始化器
    3. 设置所有可用程序监听器
    4. 推断并设置 main 的定义类

    yaml 使用

    基础使用

    #properties k=v,只能保存键值对
    #yaml 是 k:v 对空格要求较高,能注入到配置类中
    
    #普通的 key-value
    name: zhangsan
    
    #对象
    student:
      name: zhangsan
      age: 18
    
    #行内写法
    people: {name:zhangsan,age:3}
    
    #数组
    pets:
      - cat
      - dog
      - pig
    
    pet: [cat,dog,pig]
    

    可以给实体类赋值

    • 实体类

    @ConfigurationProperties作用:

    1. 将配置文件中配置的每一个属性的值,映射到这个组件中;
    2. 告诉 springboot 将本类中所有属性和配置文件相关的配置进行绑定
    3. 参数prefix = "person";将配置文件的 person 下的所有属性进行一一对应,
    4. !!!注意:只有这个组件是容器组件,才能使用这个注解
    /**
     * @ConfigurationProperties作用:配置 yalm 使用
     * 将配置文件中配置的每一个属性的值,映射到这个组件中;
     * 告诉 springboot 将本类中所有属性和配置文件相关的配置进行绑定
     * 参数prefix = "person";将配置文件的 person 下的所有属性进行一一对应,
     *
     *  !!!注意:只有这个组件是容器组件,才能使用这个注解
     */
    @Component
    @ConfigurationProperties(prefix = "person")
    //@PropertySource(value = "classpath:application.properties")//加载指定配置文件
    public class Person {
    
       // @Value("${name}")使用 properties 取值
        private String name;
        private Integer age;
        private  Boolean happy;
        private Date birth;
        private List<Object> list;
        private Map<String,Object> map;
        private Dog dog;
    
    • YAML
    person:
      name: 张三
      age: 3
      happy: false
      birth: 2020/01/01
      list:
        - code
        - music
        - sport
    # 注意 key 后面空格
      map: {k1: v1,k2: v2}
      dog:
        name: 旺财
        age: 3
    

    image-20210204154448508

    配置官方提供的依赖即可

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
    

    JSR303 校验

    spring-boot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。

    导入依赖

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
        <version>2.3.7.RELEASE</version>
    </dependency>
    
    

    将注解添加到需要校验的字段上

    img

    img

    yaml多配置

    #springboot 可以多环境配置,切换通过 active 激活
    server:
      port: 8081
    spring:
      profiles:
        active: dev
    ---
    server:
      port: 8082
    spring:
      profiles: dev
    ---
    server:
      port: 8083
    spring:
      profiles: test
    

    自动装配原理

    1. springboot 启动会加载大量的自动配置类,这个类是通过通过@ springbootApplication下的@EnableAutoConfiguration中的,AutoConfigurationImportSelector类最终找到,装配META-INF/spring.factories

    2. 我们看我们需要的功能有没有在 springboot 默认下号的自动配置类中,若配置类中以及配置则可以按照规定格式直接使用,无序手动配置

    3. 给容器中自动装配添加组件的时候,会从 properties 中获取属性,我们只需要在配置文件中指定这些属性就可以了;

      xxxxAutoConfiguration:自动配置类;给容器组件

      xxxproperti:封装配置文件中的相关属性

      (类似的配置类)

    1.springboot 会自动装配,通过xxxAutoConfiguration类自动装配,
    2.若修改默认值属性,通过xxxProperties类加载一些属性
    3.xxxProperties类和配置文件绑定,我们就可以使用按照规则自定义配置了
    
    debug=true 可以查看哪些配置类生效,哪些没生效,默认 false
    

    image-20210204233120705

    一些常见的候选功能注解

    IMG_1608

    SpringBoot Web 开发

    • xxxxAutoConfiguration 向容器中自动配置组件
    • xxxxproperties:自动配置类,装配配置文件中的自定义的一些内容

    web 开发解决那些问题

    • 导入静态资源问题
    • 首页
    • jsp,模板引擎 Thymeleaf
    • 装配扩展 SpringMvc
    • CRUD
    • 拦截器

    静态资源

    在 springboot 中可以使用以下方式处理静态资源

    1. webjars (这里是通过 maven 资源依赖导入;https://www.webjars.org/) localhost:8080/webjars/
    2. resources/public;resources/static;resources/resource 访问路径 localhost:8080/资源名 即可访问注意不是 resources 包的根下
    3. 优先级 resource>static>public

    image-20210205102505530

    • 自定义访问路径

    image-20210205103141515

    thymeleaf模板引擎

    • 导入依赖
    <!--        thymeleaf,我们都是基于 3.x 开发-->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
            </dependency>
            <dependency>
                <groupId>org.thymeleaf.extras</groupId>
                <artifactId>thymeleaf-extras-java8time</artifactId>
            </dependency>
    
    • 将 html 页面放在 Templates 目录下即可

    image-20210205141043894

    • 具有使用
    @Controller
    public class HelloController {
    
        @RequestMapping("/test")
        public String test(Model model){
            model.addAttribute("msg", "<h1>hello,springboot</h1>");
            model.addAttribute("users", Arrays.asList("张三","李四"));
            return "test";
        }
    }
    
    <!DOCTYPE html>
    									<!--需要导入-->
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <!--所有的 html 元素都可以被 thymeleaf 替换接管,th:元素名-->
    <!--不转义 取值-->
    <h1 th:text="${msg}"></h1>
    
    <!--转义 取值-->
    <h1 th:utext="${msg}"></h1>
    
    <!--元素遍历 user 是遍历出来的每个元素-->
    <h2 th:each="user:${users}" th:text="${user}"></h2>
    </body>
    </html>
    
    • 结果

    image-20210205144130004

    SpringBoot配置

    在 springboot 看到xxxxConfigurer(类似WebMvcConfigurer)会帮助我们拓展配置

    1. 首页配置:注意点,所有页面的静态资源都需要使用 thymeleaf接管,url 使用@{}
    2. 页面国际化

    springboot 整合 jdbc

    springboot 整合 Mybatis

    SpringSecurity

    shiro 和 SpringSecurity:很像 除了类不一样,名字不一样

    认证,授权

    • 功能权限
    • 访问权限
    • 菜单权限
    • —拦截器,过滤器:大量原生代码—— 冗余

    SpringBoot任务

    异步任务

    我们通过注解可以告诉 spring这是异步任务,从而完成响应。

    • service 层
    @Service
    public class AsyncService {
    
        @Async//告诉 spring 这是异步的方法
        public void test(){
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("正在执行处理。。。。");
        }
    }
    
    • controller
    @EnableAsync//开启异步处理
    @RestController
    public class AsyncController {
    
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/test")
        public String test() {
            asyncService.test();
            return "处理完成";
        }
    }
    

    定时任务

    @EnableScheduling//开启定时功能的注解	写在启动类上
    @Scheduled	//特定时间执行这个方法,写在方法上
    //cron 表达式
    //秒,分,时,日,月,周几
    
    @EnableScheduling//开启定时功能的注解
    @SpringBootApplication
    public class Springboot05TestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(Springboot05TestApplication.class, args);
        }
    
    }
    
    @Service
    public class ScheduleService {
    
        //特定时间执行这个方法
    
        //cron 表达式
        //秒,分,时,日,月,周几
        @Scheduled(cron = "0 54 12 * * ?")
        public void test(){
            System.out.println("test 已经执行了");
        }
    }
    

    SpringBoot邮件任务

    springboot中发送邮件的主要 bean 对象 JavaMailSender

    • 导入依赖
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
    
    • 配置文件
    spring.mail.username=714860063@qq.com
    spring.mail.password=授权码不是邮箱密码)
    spring.mail.host=smtp.qq.com
    #开启加密验证(qq 邮箱需设置)
    spring.mail.properties.mail.smtl.ssl.enable=true
    
    • 测试
    @SpringBootTest
    class Springboot05TestApplicationTests {
        @Autowired
        JavaMailSender javaMailSender;
    
        @Test
        void contextLoads(){
            //简单邮件发送
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject("主题");
            mailMessage.setText("发送内容");
            mailMessage.setTo("发送给谁");
            mailMessage.setFrom("谁发送的邮箱");
            javaMailSender.send(mailMessage);
        }
        
    
        @Test
        void contextLoads2() throws MessagingException {
            //复杂邮件邮件
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//参数 2 true 开启 多文件 格式
            helper.setSubject("主题");
            helper.setText("<p style='color:blue'>内容</p>",true);//开启 html 文本
           // helper.addAttachment("名称", new File("文件地址"));//附近
            helper.setTo("714860063@qq.com");
            helper.setFrom("714860063@qq.com");
            javaMailSender.send(mimeMessage);
        }
    
    }
    
    悲观者正确,乐观者成功
  • 相关阅读:
    angular-utils-pagination 使用案例
    解决mongodb ISODate相差8小时问题
    Android HttpClient POST JSON Restful-web-services
    将Map转换为Java 对象
    request.getParameterMap()
    angular-fullstack test
    oracle insert &字符插入问题
    listview底部增加按钮
    IDE 常用快捷键记录
    一个jQuery扩展工具包
  • 原文地址:https://www.cnblogs.com/freebule/p/14462600.html
Copyright © 2011-2022 走看看