美文网首页
SpringBoot入门

SpringBoot入门

作者: 红领巾三道杠 | 来源:发表于2018-02-27 14:20 被阅读0次

1. 什么是SpringBoot

  • 简化新Spring应用的初始搭建及开发过程。

  • 使用特定方式进行配置,开发人员不再需要定义样板化配置。

  • 个人理解并不是新框架,而是默认配置很多框架的使用方式。

2.新建SpringBoot项目

  • File -> New -> project


    image.png
  • 选择Spring Initializr,Next


    image.png
  • Group 输入组织例如“com.hnzskj”, Artifict输入项目名称 "hello",Type 默认 Maven Project,Language ,Packaging 选择项目打包方式,可以为war/jar。选择Java版本。Next

image.png
  • 选择项目所需要的框架,这里基本包含所有的常用框架,不再过多描述。Next
image.png
  • next,等待下载项目模板和Maven项目依赖
image.png

至此,一个SpringBoot项目创建完毕。

SpringBoot项目pom文件:
<?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>

    <groupId>com.example</groupId>
    <artifactId>hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>hello</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2. Springboot创建HelloWorld

只需要加入@RestController注解,不需要编写任何xml文件指定controller扫描包就可以执行。

@RestController
public class HelloWorldController {
    @RequestMapping(value = "hello",method = RequestMethod.GET)
    public String sayHello() {
        return "Hello,World";
    }
}

通过启动HelloApplication中的mian方法启动项目

@SpringBootApplication
public class HelloApplication {

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

浏览器输入:localhost:8080/hello,看到Hello,World


image.png

Springboot自带pom文件中包含启动项目所需要的容器,因此不需要再手动进行配置Tomcat。

3. SpringBoot创建单元测试

spring-boot-starter-test默认包含mock和junit依赖

开发环境建议编写单元测试,减少修改成本。打包时不建议跳过测试。

package com.zskj.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MockServletContext.class)
public class HelloWorldControllerTest {

   private MockMvc mockMvc;

   @Before
   public void setUp() {
       mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
   }

   @Test
   public void sayHello() throws Exception {
       mockMvc.perform(MockMvcRequestBuilders.get("/hello")
               .accept(MediaType.APPLICATION_JSON))
               .andExpect(MockMvcResultMatchers.status().isOk())
               .andDo(MockMvcResultHandlers.print())
               .andReturn();
   }
}

4. 热部署

添加POM依赖

<!-- 热部署调试 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>

配置插件

<plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
   <!-- 开发环境调试设置 -->
   <configuration>
      <fork>true</fork>
   </configuration>
</plugin>

5. Json接口开发

使用@RestController注解声明,不需要再配置RequestBody

package com.zskj.controller;

import com.zskj.Enums.SexEnum;
import com.zskj.bean.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @描述: .
 * @作者: chengzx
 * @创建时间 2018/2/24
 * @版本 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    public User getUser(){
        User user = new User();
        user.setAddress("郑州市");
        user.setAge(30);
        user.setName("中审科技");
        user.setSex(SexEnum.M);
        return user;
    }
}

6. 自定义property

application.properties中添加自定义配置

    # 测试自定义配置 
    hello=hello
    aaa=bbb

测试代码

    @Value("${hello}")
    private String name;

    @RequestMapping(value = "hello", method = RequestMethod.GET)
    public String sayHello() {
        return "Hello," + name;
    }

SpringBoot可以根据开发环境、生产环境生成多个配置文件,通过spring.profiles.active来指定生效的配置文件。子配置文件可以用 - 进行连接:

spring.profiles.active = dev

生效的文件为 application-dev.properties
配置文件先从指定的子配置文件中找,如果子配置文件中有,则从子配置文件中获取,子配置文件没有的再从根配置文件获取。

直接在使用@Value("${配置名称}")的方式获取配置文件中的值。

7. SpringBoot打包

打jar包

idea中maven窗口的install按钮可以直接打包到target目录下

打完jar包之后可以在服务器上直接java -jar xxx.jar启动。

java -jar xxx.jar 

这样关闭控制台后服务也会关闭。

可以在命令后添加 & 使服务进行后台运行

java -jar xxx.jar &

也可以在启动时候添加配置,比如指定需要使用的配置文件

java -jar xxx.jar --spring.profiles.active=dev

打war包

需要在pom文件中指定打包方式为war

    <packaging>war</packaging>

打包时排除tomcat:

在这里将scope属性设置为provided,这样在最终形成的WAR中不会包含这个JAR包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

8. SpringBoot整合Mybatis

配置文件:

application.properties指定数据源和mybatis相关配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.neo.entity
#数据源配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://47.94.240.184:3306/cheng?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=czx114132

mybatis-config.xml
指定别名,也可以添加一些其他的mybatis基础配置

<configuration>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>

User映射文件

<mapper namespace="com.neo.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="userName" property="userName" jdbcType="VARCHAR" />
        <result column="passWord" property="passWord" jdbcType="VARCHAR" />
        <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, userName, passWord, user_sex, nick_name
    </sql>

    <select id="getAll" resultMap="BaseResultMap"  >
       SELECT 
       <include refid="Base_Column_List" />
       FROM users
    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT 
       <include refid="Base_Column_List" />
       FROM users
       WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="com.neo.entity.UserEntity" >
       INSERT INTO 
            users
            (userName,passWord,user_sex) 
        VALUES
            (#{userName}, #{passWord}, #{userSex})
    </insert>

    <update id="update" parameterType="com.neo.entity.UserEntity" >
       UPDATE 
            users 
       SET 
        <if test="userName != null">userName = #{userName},</if>
        <if test="passWord != null">passWord = #{passWord},</if>
        nick_name = #{nickName}
       WHERE 
            id = #{id}   
     </update>

    <delete id="delete" parameterType="java.lang.Long" >
       DELETE FROM
             users 
       WHERE 
             id =#{id}    
    </delete>
    
</mapper>

Dao层代码

public interface UserMapper {
    List<UserEntity> getAll();
    UserEntity getOne(Long id);    
    void insert(UserEntity user);    
    void update(UserEntity user);    
    void delete(Long id);
}

Controller层代码

@RestController
public class UserController {
    
    @Autowired
    private UserMapper userMapper;
    
    @RequestMapping("/getUsers}")
    public List<UserEntity> getUsers() {
        List<UserEntity> users=userMapper.getAll();
        return users;
    }
    
    @RequestMapping("/getUser")
    public UserEntity getUser(Long id) {
        UserEntity user=userMapper.getOne(id);
        return user;
    }
    
    @RequestMapping("/add")
    public void save(UserEntity user) {
        userMapper.insert(user);
    }
    
    @RequestMapping(value="update")
    public void update(UserEntity user) {
        userMapper.update(user);
    }
    
    @RequestMapping(value="/delete/{id}")
    public void delete(@PathVariable("id") Long id) {
        userMapper.delete(id);
    }
}

单元测试代码:

Mapper测试


@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper UserMapper;

    @Test
    public void testInsert() throws Exception {
        int size = UserMapper.getAll().size();
        UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));
        UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));
        UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));
        Assert.assertEquals(size + 3, UserMapper.getAll().size());
    }

    @Test
    public void testQuery() throws Exception {
        List<UserEntity> users = UserMapper.getAll();
        if (users == null || users.size() == 0) {
            System.out.println("is null");
        } else {
            for (UserEntity user : users) {
                System.out.println(user.toString());
            }
        }
    }

    @Test
    public void testUpdate() throws Exception {
        UserEntity user = UserMapper.getOne(31L);
        System.out.println(user.toString());
        user.setNickName("neo");
        UserMapper.update(user);
        Assert.assertTrue(("neo".equals(UserMapper.getOne(31L).getNickName())));
    }

}

Controller测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象
    }

    @Test
    public void getUsers() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/getUsers")
                .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
    }

}

相关文章

网友评论

      本文标题:SpringBoot入门

      本文链接:https://www.haomeiwen.com/subject/htuyxftx.html