手把手初认Springboot2

Springboot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

Springboot是Spring中的一个成员,可以简化Spring,SpringMVC的核心是IOC容器

使用Springboot开发效率高。

Springboot特点

  1. 独立运行的 Spring 项目

Spring Boot 可以以 jar 包的形式独立运行,Spring Boot 项目只需通过命令“ java–jar xx.jar” 即可运行。

可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;

  1. 内嵌 Servlet 容器

Spring Boot 使用嵌入式的 Servlet 容器(例如 Tomcat、Jetty 或者 Undertow 等),应用无需打成 WAR 包 。

  1. 提供 starter 简化 Maven 配置

Spring Boot 提供了一系列的“starter”项目对象模型(POMS)来简化 Maven 配置。

  1. 提供了大量的自动配置

Spring Boot 提供了大量的默认自动配置,来简化项目的开发,开发人员也通过配置文件修改默认配置。

尽可能自动配置Spring容器

  1. 自带应用监控

Spring Boot 可以对正在运行的项目提供监控。

  1. 无代码生成和 xml 配置

Springboot特性

    遵循习惯优于配置的原则。使用springboot我们只需要很少的配置,大多数使用默认配置即可

    内嵌servlet容器,降低了对环境的要求,可用命令直接执行项目

    项目快速搭建。springboot尽可能自动配置spring以及第三方库,帮助开发者快速搭建spring框架,可无需配置的自动整合第三方框架

    提供各种starter简化Maven配置。springboot提供了一系列的starter用来简化maven依赖。如:常用的spring-boot-starter-web、spring-boot-starter-tomcat等

    独立运行spring项目。springboot可以以jar包的形式进行独立运行,使用java -jar xx.jar 就可以成功运行项目,无需部署war文件

    可以完全不使用xml配置,只需要自动配置和Java config

    应用监控(SpringBootActuator)

XML与JavaConfig

Spring使用XML作为容器配置文件,在3.0后加入了JavaConfig,使用java类做配置文件使用。

JavaConfig

JavaConfig:是Spring提供使用java类配置容器(代替XML配置。配置Spring IOC容器的纯Java方法。

JavaConfig类可以创建java对象,把java对象放入spring容器中(注入)。

可以使用面向对象方式,一个配置类可以继承配置类,可以重写方法。

避免了繁琐的XML配置

Springboot常用注解

@SpringBootApplication:放在启动类上,包含(@Target、@Retention、@Documented、@Inherited、@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan)

@Server:放在业务层的实现类上,创建server对象,注入到IOC容器

@Repository:放在dao层(持久层)的实现类上,创建dao对象,放入到容器。

Mybatis框的dao对象是由Mybatis代理生成。不需要使用@Repository注解。

@Controller:放在类的上面,创建控制器对象,注入到IOC容器中。

@RestController:放在类的上面,创建控制器对象,注入到IOC容器中。

@Component:放在类上面,创建此类的对象,放入容器中

组合注解@Controller,@ResponseBody,使用这个注解类的,里面的控制器方法的返回值都是数据。

@value:简单类型的赋值

@Autowired:可以用来注入非简单类型,支持byName,byType。单独使用@Autowired注解:默认根据类型装配。[默认byType],@Autowired注解可以出现在构造方法,方法,参数,属性,别的注解上。

//当有多个实现类对象时@Autowired和Qualifier联合使用,可以根据名称进行装配//Qualifier可以指定要执行的实现类对象

@Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配

@Resource注解是JDK扩展包中的,也就是属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(JSR-250标准中指定的注解类型。JSR是Java规范提案)

@Configuration:放在类的上面,表示该类是配置类,相当于xml配置文件。

@ImportResource:加载其他的xml配置文件,把文件中的对象注入到spring IOC容器

@Bean:放在方法上,将方法的返回值对象,注入到spring IOC容器中。

@PropertySource:读取其他的properties属性配置文件

@ComponentScan:扫描器,组件扫描,用来扫描注解

@ResponseBody:方法上或类上,表示方法的返回值是数据,不是

@RequestBoay:把请求体中的数据,读取出来,转为java对象使用。

@ControllerAdvice:控制器增强,表示此类提供了方法,可以对controller增强功能

@ExceptionHandler:处理异常,放在方法上

@Transcational:处理事务,放在service实现类的public方法上。

@Mapper:放在dao接口上,mybaits找到该接口,创建他的代理对象,将代理对象注入到spring IOC容器中

@MapperScan:放在主类的上面,指定指定的包,把包中的所有接口都创建代理对象,将代理对象注入到spring IOC容器中

@Param:dao接口方法的形参前面,作为命名参数使用。

@DubboService:提供者端使用,暴露服务,放在接口的实现类上

@DubboReference:在消费者端使用,引用远程服务,放在属性上面使用。

@EnableDubbo:放在主类上面,表示启用Dubbo功能

XML配置文件配置与JavaConfig配置注入IOC容器

pojo类

public class Student {

    private String name;

    private int age;

    private String sex;
       //get+set+toString
}

分别使用XML配置与JavaConfig配置方式将Student对象注入IOC容器

XML配置文件配置

springConfig.xml

<bean id="student" class="com.qgs.pojo.Student">

    <property name="name" value="张三"></property>

    <property name="age" value="18"></property>

    <property name="sex" value="男"></property>

</bean>

测试类

@Test

public void test01(){

    ApplicationContext applicationContext =new ClassPathXmlApplicationContext("springConfig.xml");

    Student student = applicationContext.getBean("student", Student.class);

    System.out.println(student.toString());

}

JavaConfig配置@Configuration

/**

 * @Configuration注解:表示该类作为配置文件使用。用来配置IOC容器。

 * 使用@Configuration注解后SpringConfig类,代替springConfig.xml

 */

@Configuration

public class SpringConfig {

    /**

     * 创建方法其返回值为对象,加入@Bean注解后,对象就注入到IOC容器中

     */
       //未使用@Bean注解来指定Bean的名字则默认为方法名

    @Bean

    public Student createStudent(){

        Student st1 =new Student();

        st1.setName("李四");

        st1.setAge(20);

        st1.setSex("男");

        return st1;

    }

}

测试类

@Test

public void test02(){

    ApplicationContext aC =new AnnotationConfigApplicationContext(SpringConfig.class);

    Student createStudent = aC.getBean("createStudent", Student.class);

    System.out.println(createStudent.toString());

}

使用@bean注解指定名称

@Bean(name ="Student001")

 

引入@ImportResource

@ImportResource作用:导入其他xml配置文件,等同于

等同于在xml中使用import

<import resource="classpath:xxxx.xml"/>

@ImportResource的使用

@ImportResource(value ="classpath:applicationContext.xml")

 

@PropertyResource注解

@PropertyResource注解是读取properties属性配置文件,类似于在xml配置文件中的

<!--引入外部文件-->

<context:property-placeholder location="classpath:jdbc.properties"/>

@PropertyResource注解的使用

在resources目录下创建properties文件,使用key=value格式提供数据

创建类

@Component("jdbc")

public class Jdbc {

  @Value("${jdbc.driver}")

  private String  driver;

  @Value("${jdbc.url}")

  private String  url;

  @Value("${jdbc.user}")

  private String  user;

  @Value("${jdbc.password}")

  private String  password;

  //get + set + toString

}

SpringConfig配置

@ComponentScan({"com.qgs.pojo"})

@PropertySource(value = "classpath:jdbc.properties")

 

测试类

@Test

public void test02(){

    ApplicationContext aC =new AnnotationConfigApplicationContext(SpringConfig.class);

    Jdbc jdbc = aC.getBean("jdbc", Jdbc.class);

    System.out.println(jdbc.toString());

}

创建SpringBoot项目的方式

使用Spring提供的初始化器,向导创建springboot项目

DIEA使用国外地址:

https://start.spring.io

DIEA使用国内地址

https://start.springboot.io

 

浏览器构建项目

IDEA导入包

使用Maven构造SpringBoot项目

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.7.10</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>org.example</groupId>

    <artifactId>springboot004</artifactId>

    <version>1.0-SNAPSHOT</version>
    <properties>

        <maven.compiler.source>8</maven.compiler.source>

        <maven.compiler.target>8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    </properties>
    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>2.3.0</version>

        </dependency>
        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>com.mysql</groupId>

            <artifactId>mysql-connector-j</artifactId>

            <scope>runtime</scope>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

    </dependencies>
    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>
</project>

@SpringBootApplication注解

@SpringBootApplication注解由

@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan

组成

@SpringBootApplicatio

@SpringBootConfiguration

@SpringBootConfiguration注解标注的类,可以作为配置文件使用,可以声明Bean对象,注入容器中。

@EnableAutoConfiguration

@EnableAutoConfiguration注解:启动自动配置,将java对象配置好,注入到Spring容器中。列如将Mybatis的对象创建好注入Spring容器中。

@ComponentScan组件扫描器。根据注解功能创建对象,属性赋值。

Spring Boot核心配置文件

Spring Boot核心配置文件用于配置Spring Boot程序,名字以application开始

Spring Boot默认使用Properties配置文件

Properties配置文件

使用application.properties可以配置端口,web根路径等

#设置端口号
server.port=8080
#设置访问路径 contextPath
server.servlet.context-path=/boot

Yml配置文件

YAML (YAML Ain’t a Markup Language)YAML不是一种标记语言,通常以.yml为后缀的文件,是一种直观的能够被电脑识别的数据序列化格式,并且容易阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,一种专门用来写配置文件的语言。

YML语法

    k: v 表示键值对关系,冒号后面必须有一个空格

    使用空格的缩进表示层级关系,空格数目不重要,只要是左对齐的一列数据,都是同一个层级的

    大小写敏感

    缩进时不允许使用Tab键,只允许使用空格。

    java中对于驼峰命名法,可用原名或使用-代替驼峰,如java中的lastName属性,在yml中使用lastName或 last-name都可正确映射。

    yml中注释前面要加#

Properties配置文件与Yml配置文件对比

Springboot创建多环境配文件

Whitelabel Error Page问题

产生原因:目录结构错误

方法返回值问题

返回的不是模板,而是字符串时,Controller类需要添加 注解 @RestController,或方法添加@ResponseBody

解决办法1

解决办法2

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

多环境配置

Spring Boot提供了多环境配置

每个环境有不同的ConfigInfo,Port,Context,Jdbc_url,username,password等

使用多环境配置文件,可以方便的切换不同的配置。

开发环境、生产环境、测试环境。

名称规则:application-环境名称.properties(yml)

开发环境::application-dev. yml

生产环境: application-produce.yml

测试环境:application-test.yml

Spring Boot默认使用application.properties

#application.properties配置文件

##设置端口号

#server.port=8080

##设置访问路径 contextPath

#server.servlet.context-path=/boot
#使用哪个配置环境

spring.profiles.active=dev

#application.yml配置文件

#使用哪个配置环境

spring:

  profiles:

    active: dev

#开发环境配置

server:

  port: 8081

  servlet:

    context-path: /dev

#生产环境配置

server:

  port: 8083

  servlet:

    context-path: /produce

#测试环境配置

server:

  port: 8082

  servlet:

    context-path: /test

Spring Boot自定义配置

@Value注解

使用@value注解获取自定义参数

#application.properties配置文件

##设置端口号

server.port=8080

##设置访问路径 contextPath

server.servlet.context-path=/boot
#自定义key=value

t.name=qgs

t.age=3

t.address=深圳
@Value("${server.port}")

private int port;

@Value("${server.servlet.context-path}")

private String contextPath;

@Value("${t.name}")

private String name;

@Value("${t.age}")

private int age;

@Value("${t.address}")

private String address;
@RequestMapping("/hello")

@ResponseBody

public String getDateValue(){

    return port+"  "+contextPath+"  "+name+"/  "+age+"  "+address;

}

@ConfigurationProperties注解

将配置文件的数据映射为一个对象,用于自定义配置项较多的情况

pom.xml配置

<!--        处理ConfigurationProperties元数据-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-configuration-processor</artifactId>

            <optional>true</optional>

        </dependency>

@ConfigurationProperties(prefix = "t")

springmvc测试

SpringBoot使用JSP

SpringBoot不推荐使用JSP,推荐使用模板技术代替JSP

pom.xml文件配置

加入依赖

<dependency>

    <groupId>org.apache.tomcat.embed</groupId>

    <artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

</dependency>

<dependency>

    <groupId>javax.servlet.jsp</groupId>

    <artifactId>javax.servlet.jsp-api</artifactId>

    <version>2.2.1</version>

</dependency>

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>jstl</artifactId>

</dependency>

创建webapp目录

pom.xml文件配置

<!--指定jsp编译后的存放目录-->

<resources>

    <resource>

        <!--原目录-->

        <directory>src/main/webapp</directory>

        <!--指定要处理的目录和文件 **/*.*表示任意文件和子目录的任意文件-->

        <includes>

            <include>**/*.*</include>

        </includes>

        <!--指定编译后的存放目录-->

        <targetPath>META-INF/resources</targetPath>

    </resource>

</resources>

Controller

@Controller

public class JspController01 {

    @Resource

    private StudentInfo sInfo;

    @RequestMapping("/jsp")

    public String doJsp(Model model){
        //model将数据放入到request作用域

        model.addAttribute("sInfo",sInfo);  //model == request.setAttribute("sInfo",sInfo);
        return "index";

    }
}

application.properties配置视图解析器

#配置视图解析器

# / 表示在webapp目录下

spring.mvc.view.prefix=/

spring.mvc.view.suffix=.jsp

Index.jsp

<body>

<h3>姓名:${sInfo.name} 年龄:${sInfo.age} 地址:${sInfo.address}</h3>

</body>

Spring Boot 使用ApplicationContext获取容器对象

在main方法中SpringApplication.run()方法获取返回的Spring容器对象,在获取业务bean进行调用。

public static void main(String[] args) {

    //获取容器对象

    ConfigurableApplicationContext run = SpringApplication.run(StudentApplication.class, args);

    StudentInfo studentInfo = (StudentInfo) run.getBean("studentInfo");

    System.out.println(studentInfo.toString());

}

使用CommandLineRunner接口

在开发过程中会有在容器启动后执行一些内容。如连接数据库,读取配置文件等。SpringBoot提供了两个接口:CommandLineRunner和ApplicationRunner,来实现,这两个接口中有一个run方法。两个接口的不同之处是:CommandLineRunne中的run方法参数为String数组,而ApplicationRunner中的run方法参数为ApplicationArguments。

如有错误请指正,谢谢

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QGS-CD

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值