SpringBoot的使用

SpringBoot

为什么使用SpringBoot?

Spring优缺点分析:

优点:Spring通过依赖注入和面向切面编程,以相对简单的方式实现了EJB (Enterprise JavaBeans) 的功能。

缺点:1.无论是Spring2.5版本以前使用XML进行配置,还是Spring2.5以后使用基于注解的组件扫描都会降低开发效率,编写配置挤占了编写应用程序逻辑的时间。

2.在环境搭建时,项目的依赖管理可能会由于依赖库的版本不兼容阻碍项目的开发进度。

SpringBoot概述:

SpringBoot对上述Spring的缺点进行了改善和优化,基于约定大于配置的思想,减少了配置的繁杂步骤,提高了开发效率;并且通过起步依赖(Starter)实现了库的传递依赖,一定程度上避免了依赖库的版本冲突。

SpringBoot启动

第一种方式:从file中直接启动spring-boot项目(不推荐)

第二种方式:启动Maven项目

1 创建Maven工程

使用idea工具创建一个maven工程,该工程为普通的java工程即可

2 添加起步依赖

SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
</parent>

SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖

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

注:切换服务器方法(可选项):

pom配置文件中exclusions标签标识要排除的依赖包,如果用exclusions标签排除spring-boot-starter-tomcat。

引入spring-boot-starter-undertow依赖,引入JBOSS服务器,可以支撑大型应用。代替tomcat。

3 编写SpringBoot引导类

要通过SpringBoot提供的引导类起步SpringBoot才可以进行访问

@SpringBootApplication
public class PropertyApplication {

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

}

SpringBootApplication:复合注解,底层由以下三种注解组成:

SpringBootConfiguration表示当前启动的主类也是一个配置类,可以再主类中进行一些bean的配置

EnableAutoConfiguration这个注解标识启用自动装备

ComponentScan这个注解标识组件扫描,如果没有配置扫描的包,那么就会扫描当前主类所在的包。

4 编写Controller

在引导类PropertyApplication同级包或者子级包中创建UserController

@RestController
public class UserController {
    
    @GetMapping("/welcome")
    public String welcome(){
        return "welcome to springboot";
    }
}
5 测试

执行SpringBoot起步类的主方法,服务器启动成功后打开浏览器地址栏访问

打开浏览器访问url地址为:http://localhost:8080

SpringBoot配置文件

1.配置文件类型

SpringBoot的配置文件有三种类型:

  • properties
  • yml
  • yaml

SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件。

在 Spring Boot 项目中,application.propertiesapplication.yml 是用于配置应用程序的两种不同格式的配置文件。可以选择其中之一进行使用,也可以同时存在,它们的配置会被合并。(名字必须为application)

一般来说,Spring Boot 会根据以下顺序加载配置文件:

  1. application.yml
  2. application.properties

如果相同的配置项在两个文件中都存在,那么 application.properties 中的配置会覆盖 application.yml 中的配置。这是因为 application.properties 被加载的优先级更高。

经验:一般使用yml文件,因为写法更简单。

2.yml配置文件语法
  • 配置普通数据

    • 语法:

       key: 属性值 #注意:冒号后面有个空格
      
    • 示例:

      port: 9000 
      
  • 配置对象数据/Map数据

    • 语法:

      key: 
        属性名1: 属性值1
        属性名2: 属性值2
      
    • 示例代码:

      server:
        port: 9000
      

    注意:在yml语法中,相同缩进代表同一个级别

  • 配置数组(List、Set)数据

    • 语法:

      key:
        - 值1
        - 值2
      
      key:
        [值1, 值2]
      
    • 示例代码:

      ages:
        - 20
        - 22
        - 24
        
      ages:
        [20, 22, 24]
      

    注意:value1与value2之间的 - 之间存在一个空格

3.修改默认配置

可以通过配置application.poperties 或者 application.yml 来修改SpringBoot的默认配置

例如:

application.properties文件

server.port=9000
server.servlet.context-path=property

application.yml文件

server:
  port: 9000
  servlet:
    context-path: /property

配置文件与配置类的属性映射方式

1.使用注解@Value映射

先进行配置:

person:
  name: zhangsan
  age: 18

实体Bean代码:

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;


    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome to springboot, name="+name+",age="+age;
    }

}
2.使用@ConfigurationProperties映射

application配置不变,实体Bean代码如下:

@RestController
@RequestMapping("/user")
@ConfigurationProperties(prefix = "person")
public class UserController {

    private String name;
    private Integer age;

    @GetMapping("/welcome")
    public String welcome(){
        return "welcome to springboot, name="+name+",age="+age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

注意:使用@ConfigurationProperties方式可以进行配置文件与实体字段的自动映射,但需要字段必须提供set方法才可以,而使用@Value注解修饰的字段不需要提供set方法.

3.如果引用的数据类型为集合

不能在controller层中直接使用application配置中的集合,如果要使用,需要将集合配置为一个对象的属性,然后创建配置类,配置类中需要加上@ConfigurationProperties(prefix = “集合中对象名”)注解,用于配置前缀,就是application配置文件中的对象名。配置类中的集合属性需要加上get方法。

my:
  usernames:
    - zhangsan
    - lisi
@ConfigurationProperties(prefix = "my")
public class UserConfig {

    private List<String> usernames;

    public List<String> getUsernames() {
        return usernames;
    }

    public void setUsernames(List<String> usernames) {
        this.usernames = usernames;
    }
}

然后在controller层中持有配置类对象作为属性,加上@Autowired注解使其自动从ioc容器中注入内容,然后调用对象的get方法得到集合。这里需要加上@EnableConfigurationProperties(UserConfig.class)注解,以将配置文件生效。

@RestController
@EnableConfigurationProperties(UserConfig.class)
public class MyController {
    @Autowired
    private UserConfig userConfig;
    @GetMapping("/welcome")
    public String welcome(){
        return "welcome to springboot" +userConfig.getUsernames();
    }
}

整合mybatis:

1.添加依赖:
<!--mybatis起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.0</version>
</dependency>
<!--MySQL连接驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>

2.添加数据库连接信息
mybatis:
  mapper-locations: mapper/*Mapper.xml
  type-aliases-package: com.qf.springboot.pojo
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource #默认采用的就是光连接池
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/lesson?serverTimezone=Asia/Shanghai
    username: root
    password: 123456
3.测试

mapper层:

@Mapper
public interface UserMapper {
    User getUserByUsername(@Param("username") String username);
}

userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qf.springboot.mapper.UserMapper">
    <select id="getUserByUsername" resultType="user">
        select * from user
        <where>
            <if test="#{username}!=null and #{username!=''}">
                AND username = #{username}
            </if>
        </where>
    </select>
</mapper>

service:

public interface UserService {

    User getUserByUsername(String username);
}
//----------------------------------------------------------------------
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }
}

controller:

@RestController
@RequestMapping("/user")

public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{username}")
    public User getUser(@PathVariable("username") String username){
        return userService.getUserByUsername(username);
    }
}

整合 Junit

1 添加依赖
<!--测试的起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
2 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PropertyApplication.class)
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test(){
        User user = userMapper.getUserByUsername("zs");
        System.out.println(user);
    }
}

注意:必须放在src/test包下。

其中,SpringRunner继承自SpringJUnit4ClassRunner,使用哪一个Spring提供的测试测试引擎都可以

public final class SpringRunner extends SpringJUnit4ClassRunner 

@SpringBootTest的属性指定的是引导类的字节码对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值