SpringBoot简直丧心病狂

303 阅读2分钟

「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战」。

#简介

#环境搭建

POM

  • 关于搭建个Springboot项目非常简单。我们只需要在pom中继承springboot就行
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.3.RELEASE</version>
</parent>
  • 因为我们搭建springboot都是用来做web的。所以在引入web模块的依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 然后就是springboot打包需要的插件
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
  • 至此,我们的pom环节设置完成了。我们离搭建完成还缺一个启动类

#启动类

@SpringBootApplication
public class CrontabApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrontabApplication.class, args);
    }
}
​
  • 就是上面一个main函数。在类上加上@SpringbootApplication。就这么简单。到这里我们springboot项目搭建就结束了。运行就不说了。

整合数据库

  • 上面两步骤我们就完成了搭建springboot项目。这个时候项目就是一个空壳项目。既然是web项目我们就离不开数据库。接下来我们来整合mybatis和mysql数据库。
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.15</version>
</dependency>
  • 因为springboot为我们提供了很多默认的配置。所以我们这里将数据库引入,之后只需要在配置文件中配置数据库信息就可以了。

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/crontab?serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

  • 接下来我们就写一个接口来操作数据库试试。为了方便测试这里我们就不配置xml了。直接通过注解方式编写
@Mapper
public interface TestMapper {
​
    /**
     * 获取数据集合
     * @return
     */
    @Select("select * from Test")
    public List<Test> getTests();
​
}
​
  • 然后我们编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CrontabApplication.class)
public class Test {
​
    @Autowired
    private TestMapper testMapper;
​
    @org.junit.Test
    public void getTests() {
        List<com.github.zxhtom.crontab.model.Test> tests = testMapper.getTests();
        System.out.println(tests);
    }
}
​

  • 如图中我们已经将数据库信息查出来了。springboot的强大就是细节做的很到位。我们用起来很舒服。但是作为一名开发我们不能仅仅局限与使用上。入门就应该简单点。后面我们在带大家一层一层深入。