Spring Boot初级

Spring Boot

1.SpringBoot框架简介

SpringBoot可以视为一个更加简单、易用的SpringMVC框架!

当使用传统的SpringMVC框架时,就使用SpringMVC本身就需要添加一些依赖,例如spring-webmvcjackson-databind等,并且,需要做一些配置,例如在web.xml中关于DispatcherServletCharacterEncodingFilter的配置,在Spring的配置文件中关于组件扫描等配置,如果整合了Thymeleaf、MyBatis等框架,又需要再添加依赖,并添加更多的配置!其实,即使创建多个项目,所需要添加的依赖也是相对固定的,所需要添加的配置也几乎没有太大的变化,SpringBoot框架就解决了这个问题!在SpringBoot框架的项目中,默认就已经添加了常用的依赖,并且,完成了常规的配置,它是基于“约定大于配置”的思想的!

2.创建Spring Boot项目

使用Spring提供的初始化器, 就是向导创建SpringBoot应用

使用国内的地址 :https://start.springboot.io

SpringBoot项目的结构:

2.1 SpringBoot主配置类中注解的作用:

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

@SpringBootApplication 在这个注解上有两个元注解

  • @SpringBootConfiguration :使用了这个注解,说明这个类是一个配置类

  • @ComponentScan :扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。 默认扫描的包: @ComponentScan所在类的包和子包。

2.2 SpringBoot的配置文件

配置文件名称 :application.properties 或者 application.yml

扩展名有: properties( k=v) ; yml ( k: v)

例1:application.properties设置 端口和上下文

#设置端口号
server.port=8080
#设置访问应用上下文路径 ,contextPath
server.servlet.context-path=/myboot

例2: application.yml

server:
  port: 8080
  servlet:
    context-path: /myboot

2.3 多环境配置

有开发环境, 测试环境, 上线的环境

每个环境有不同的配置信息, 例如端口, 上下文件, 数据库url,用户名,密码等等

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

使用方式: 创建多个配置文件, 名称规则: application-环境名称.properties(yml)

创建开发环境的配置文件: application-dev.properties( application-dev.yml )

创建测试者使用的配置: application-test.properties

在application.yml中配置激活哪一个环境

#激活使用的test环境
spring:
  profiles:
    active: test

2.4 @ConfigurationProperties

@ConfigurationProperties: 把application.properties中的某些值映射到Java对象属性中

属性:prefix 配置文件中以key的开头的内容,映射到Java对象属性中。

application.yml

student:
  name: "zhangsan"
  id: 12
  age: 23

student类 :需要提供set方法 ,是通过set方法赋值的

@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String name;
    private Integer id;
    private Integer age;
    
    public void setName(String name) {
        this.name = name;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}

SpringBootDemoApplicationTests 测试类

@SpringBootTest
class SpringBootDemoApplicationTests {
    /**
     * 先通过byName赋值,找不到. 就会根据byType再找一次,赋值
     */
    @Resource
    private Student student;
    @Test
    public void testStudent(){
        System.out.println(student);
    }
}

3.拦截器

SpringBoot框架中使用拦截器

使用步骤:

  1. 创建拦截器对象实现HandlerInterceptor接口

  2. 注册拦截器

  • 创建拦截器对象实现 HandlerInterceptor

    /**
     * 自定义拦截器
     */
    public class LoginInterceptor implements HandlerInterceptor {
    ​
        /**
         *  @param handler  被拦截器的控制器对象
         *  @return boolean
         *      true : 请求能被Controller处理
         *      false: 请求被截断
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("执行了LoginInterceptor的preHandle");
            return true;
        }
    }
  • 注册拦截器

    @Configuration
    public class MyAppConfig implements WebMvcConfigurer {
        //添加拦截器对象,注入到容器中
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 创建拦截器对象
            HandlerInterceptor interceptor = new LoginInterceptor();
            //指定拦截的请求uri地址
            String[] path = {"/user/**"};
            //指定不拦截的地址
            String[] excludePath = {"/user/login"};
            registry.addInterceptor(interceptor)
                    .addPathPatterns(path)
                    .excludePathPatterns(excludePath);
        }
    }

4. 配置请求响应编码方式

修改application.properties文件

server:
  port: 8080
  servlet:
    context-path: /myboot
    encoding:
      #让系统的CharacterEncdoingFilter生效
      enabled: true
      #指定使用的编码方式
      charset: utf-8
      #强制request,response都使用charset属性的值
      force: true

5.1 连接数据库

如果创建项目时,并没有添加mysqlmybatis的依赖,则需要在pom.xml中补充:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

当添加以上依赖后,项目就无法直接启动了,启动失败的原因是:当添加了数据库相关依赖后,SpringBoot项目在启动时,就会尝试读取连接数据库的配置信息,如果这些配置信息尚不存在,则会报错!所以,需要先在application.properties中添加配置信息:

spring.datasource.url=jdbc:mysql://localhost:3306/dongsheng?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=***

添加以上配置后,项目就可以正常启动了,但是,在启动过程中,只会读取配置信息,并不会尝试连接数据库,所以,即使配置信息有误,也不影响项目启动!

接下来,应该迅速检查以上配置是否正确,当前项目是否可以连接到数据库!

在项目的src/test/java下默认就存在有一个测试包,并且,包中有SampleApplicationTests类,类中有空白的contextLoads()方法,这个方法的作用就是检验测试环境是否正常的方法,应该先通过单元测试执行该方法。

在SpringBoot项目中,所有的单元测试类都必须放在测试根包下!

在SpringBoot项目中,执行单元测试时,会加载整个项目的所有环境,包括各种配置、Spring容器等。

接下来,在SampleApplicationTests中添加单元测试方法,以测试是否可以连接到数据库:

@Autowired
DataSource dataSource;
    
@Test
public void getConnection() throws SQLException {
    Connection conn = dataSource.getConnection();
    System.err.println(conn);
}

凡是以前使用Spring/SpringMVC时从Spring容器中获取的对象,在SpringBoot的单元测试中,都可以通过自动装配来获得值!

5.2 数据库编程

目标:插入用户数据。

使用MyBatis实现数据库编程时,需要先设计抽象方法,抽象方法必须在接口中,所以,需要先创建接口,再声明抽象方法!同时,插入用户数据时,会使用到多个参数,可以将这些参数都封装在自定义的类中,再将这个类型的数据作为抽象方法的参数!

先在com.dongsheng.sample下创建子级的entity包,并在这个包中声明User类:

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String phone;
    private String email;
}

然后,在com.dongsheng.sample下创建子级的mapper包,并在这个包中创建UserMapper接口,并在接口中添加抽象方法:

public interface UserMapper {   
    Integer addnew(User user);
}

接下来,需要配置接口文件的位置,可行的做法有:

  • 直接在接口的声明之前添加@Mapper注解,这种做法就要求每个接口之前都需要添加注解;

  • 配置类的声明之前添加@MapperScan注解,并配置接口所在的包,只需要配置1次即可。

在基于Spring框架中的项目中,添加了@Configuration注解的类就是配置类

在SpringBoot项目中,启动类之前添加了@SpringBootApplication注解,该注解是基于@SpringBootConfiguration的,而@SpringBootConfiguration是基于@Configuration的,所以,SpringBoot项目中的启动类本身也是配置类!

所以,关于接口文件的配置,可以在启动类之前添加注解来实现配置:

@SpringBootApplication
@MapperScan("com.dongsheng.sample.mapper")
public class SampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
}

当声明了接口中的抽象方法后,就需要为抽象方法配置SQL语句,可以在抽象方法之前添加@Insert@Delete@Update@Select注解,并在注解参数中配置SQL语句,例如:

public interface UserMapper {
    @Insert("INSERT INTO t_user ("
        + "username,password,age,phone,email"
        + ") VALUES ("
        + "#{username},#{password},#{age},#{phone},#{email}"
        + ")")
    Integer addnew(User user);
​
}

以上这种直接在抽象方法的声明之前使用注解配置SQL语句的做法也不是SpringBoot特有的做法,是MyBatis框架本身就支持的做法,在基于XML配置的MyBatis项目中需要添加额外的配置才可以使用!另外,也不建议使用这种做法,因为使用这种做法时,很难保证篇幅较长的SQL语句的可读性,并且,需要添加其它的配置属性时,需要使用更多注解和更多配置,代码的整体可读性就会更差!所以,还是推荐使用XML文件来配置抽象方法对应的SQL语句!

接下来,在src/main/resources下创建mappers文件夹,并在该文件夹中粘贴得到UserMapper.xml,在UserMapper.xml中配置:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
    "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.dongsheng.sample.mapper.UserMapper">
    <insert id="addnew">
        INSERT INTO t_user (
            username, password, phone, age, email
        ) values (
            #{username}, #{password}, #{phone}, #{age}, #{email}
        )
    </insert>
</mapper>

使用XML配置SQL语句,就需要配置XML文件的位置,则在application.properties中添加配置:

mybatis.mapper-locations=classpath:mappers/*.xml

完成后,在src/test/javacom.dongsheng.sample包下创建mapper包,并在这个包中创建UserMapperTests测试类,并在类的声明之前添加@RunWith(SpringRunner.class)@SpringBootTest注解,并在类中编写、执行测试方法:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTests {
    @Autowired
    UserMapper mapper;
    @Test
    public void addnew() {
        User user = new User();
        user.setUsername("springboot");
        user.setPassword("8888");
        user.setAge(25);
        user.setPhone("13700137777");
        user.setEmail("springboot@163.com");
        Integer rows = mapper.addnew(user);
        System.err.println("rows=" + rows);
    }
}

在SpringBoot 2.2.x系列版本后,测试类的声明之前的注解有所变化!自定义的测试类到底加什么注解,以SpringBoot项目自带的测试类作为参考!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值