springboot 系列教程一:基础项目搭建

使用 spring boot 有什么好处


  1. 其实就是简单、快速、方便!平时如果我们需要搭建一个 spring web 项目的时候需要怎么做呢?
  2. 配置 web.xml,加载 spring 和 spring mvc
  3. 配置数据库连接、配置 spring 事务
  4. 配置加载配置文件的读取,开启注解
  5. 配置日志文件

配置完成之后部署 tomcat 调试,现在非常流行微服务,如果我这个项目仅仅只是需要发送一个邮件,或者我的项目仅仅是生产一个积分,我都需要这样折腾一遍,想想就很累!

快速入门


maven 构建项目

  1. 访问 http://start.spring.io/
  2. 选择构建工具 Maven Project、Spring Boot 版本以及一些工程基本信息,点击“ Switch to the full version. ”,可以看到更多的配置
  3. 点击 Generate Project 下载项目压缩包
  4. 解压后,使用 eclipse,Import -> Existing Maven Projects -> Next ->选择解压后的文件夹-> Finsh,OK done!

项目结构介绍

spingboot 建议的目录结果如下:

com
  +- example
    +- myproject
      +- Application.java
      |
      +- domain
      |  +- Customer.java
      |  +- CustomerRepository.java
      +- service
      |  +- CustomerService.java
      +- controller
      |  +- CustomerController.java
Application.java 建议放到根目录下面,主要用于做一些框架配置
domain 目录主要用于实体(Entity)与数据访问层(Repository)
service 层主要是业务类代码
controller 负责页面访问控制

采用默认配置可以省去很多配置,当然也可以根据自己的喜欢来进行更改最后,启动 main 方法,至此一个项目搭建好了!

官方的构建工具非常舒服,下面我选择自己创建一个maven项目,自己做配置,我的项目结构如下:

引入web模块

1.pom.xml 中添加支持 web 的模块:

<?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">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springboot</artifactId>

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

</project>

2.编写 controller 内容:

package com.bdqn.zmj.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HellController {

    @RequestMapping("/hello")
    public String index() {

        return "Hello World";
    }

}

@RestController 的意思就是 controller 里面的方法都以 json 格式输出

3.启动类

package com.bdqn.zmj.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.bdqn.zmj")
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class,args);
    }
}

3、启动 main 方法,打开浏览器访问 http://localhost:8080/hello 就可以看到效果了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章