Git+SpringBoot搭建

一、基本Spring Boot项目

1、创建Spring Boot项目

如果由于网络因素导致下载依赖工具包失败,可以找到Maven进行clean,再install,并进行刷新:

2、引入依赖

在pom.xml文件中引入MySQL依赖:

当前所有依赖如下:

    <dependencies>
        <!-- web项目启动模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- spring boot项目热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- 工具包,主要简化实体类开发 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
    </dependencies>
3、编写配置文件
# 配置项目端口号
server.port=8888

# 配置数据库连接信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

判断端口号是否被占用:

北京时间东八区:serverTimezone=GMT%2B8;上海时间:serverTimezone=Asia/Shanghai

4、测试
测试一
# 其他配置
context.name=Java
context.age=19
context.info=Hello World!
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
public class ValueController {

    @Value("${context.name}")
    private String CONTEXT_NAME;

    @Value("${context.age}")
    private int CONTEXT_AGE;

    @Value("${context.info}")
    private String CONTEXT_INFO;

    @PostConstruct
    public void getValue() {
        System.out.println("name:" + CONTEXT_NAME + ", age:" + CONTEXT_AGE + ", info:" + CONTEXT_INFO);
    }
    // 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的init()方法
    // 被@PostConstruct注解的方法将在该类中所有注入操作完成之后执行
}

测试二
# 其他配置
context.name=Java
context.age=19
context.info=Hello World!
package com.example.testboot.entity;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data   // getter/setter/toString不用手写
@Component  // 将该对象交给Spring管理
@ConfigurationProperties(prefix = "context")    // 将properties文件注入该JavaBean
public class ValueEntity {
    private String name;
    private int age;
    private String info;
}
import com.example.testboot.entity.ValueEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
public class ValueController {

    @Autowired
    private ValueEntity valueEntity;

    @PostConstruct
    public void postConstruct() {
        System.out.println("context:" + valueEntity +"--->name:" + valueEntity.getName() + ", age:" + valueEntity.getAge() + ", info:" + valueEntity.getInfo());
    }

    // 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的init()方法
    // 被@PostConstruct注解的方法将在该类中所有注入操作完成之后执行
}

@ConfigurationProperties注解的使用

@ConfigurationProperties是Spring Boot中的一个注解,用于将配置文件中的属性值映射到Java类的属性上。通过在Java类上添加@ConfigurationProperties注解,可以将配置文件中的属性值自动绑定到Java类的属性上,从而方便地获取和使用配置信息。这个注解可以用于读取application.properties或application.yml文件中的属性值,并将其注入到Spring容器中的Bean中。 ConfigurationProperties有三种使用方式:

① @Component 和 @ConfigurationProperties放在Java Bean定义类上。就是本例中的使用

② @ConfigurationProperties 和 @Bean 注解在配置类的Bean定义方法上。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfig {
    @ConfigurationProperties(prefix = "context")
    @Bean
    public String getValue(){    // 定义bean方法
    }
}

③ @ConfigurationProperties 到普通类,然后启动类添加@EnableConfigurationProperties定义为Bean。此处以第一种的代码为例,做修改即可。

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@ConfigurationProperties(prefix = "context")
@Data
public class Person implements Serializable {
    // 属性
}
import com.gwm.pojo.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

// 注解后面要加上开启配置的类(格式:类名.class)
@EnableConfigurationProperties({Person.class})
@SpringBootApplication
public class TestBootApplication{
    public static void main(String[] args) {
        SpringApplication.run(TestBootApplication.class, args);
    }
}

二、上传至GitHub

1、登录GitHub创建仓库

2、登录本地的git并push

1)打开git bash,并进入到项目文件夹中

2)输入:git init,把这个文件夹变成Git可管理的仓库

此时发现当前项目文件夹中多了一个.git文件夹:

3)输入:git add .,把该目录下的所有文件添加到仓库,注意点是用空格隔开的

可以使用git status来查看仓库当前的状态

4)输入:git commit -m "first commit",把项目提交到仓库, -m后面引号里面是本次提交的注释内容

5)输入:git remote add origin https://github.com/xxx/xxx.git,与远程仓库建立连接

6)输入:git push origin master

注意:如果输入时发现旁边没有master并且提示错误:

则需要输入:git config --global --add safe.directory '文件夹路径'

如果报如下错误,一般是因为服务器的SSL证书没有经过第三方机构的签署,所以才报错:

解决方法:输入:git config --global http.sslVerify false

三、将GitHub上clone

1)创建一个文件夹,输入git status查看状态

出现:fatal: not a git repository (or any of the parent directories): .git

2)输入:git clone https://github.com/xxx/xxx.git

由于该远程仓库有两个分支:main、dev,main是默认主分支,所以此时克隆的是main分支

进入仓库文件夹,发现括号中写的(main)

查看所有的分支git branch:

输入git checkout dev,切换到dev分支的内容,git switch main又切换回main分支内容,文件夹内容会随着分支的切换而变化。

在Git中报错:fatal: unable to access 'https://github.com/xxx/xxx.git/': Failed to connect to github.com port 443 after 33067 ms: Timed out

解决:①cmd -> ipconfig/flushdns,清除缓存(刷新 DNS 解析缓存)

②在git中输入以下内容,取消代理:

git config --global --unset http.proxy
 
git config --global --unset https.proxy

打开该项目:打开IDEA,选择clone下来的项目进行打开,并下载依赖等。

如果出现错误,则表示IDEA的maven地址设置出错,系统找不到指定的maven路径:No valid Maven installation found. Either set the home directory in the configuration dialog or set the M2_HOME environment variable on your system.

四、Spring Boot示例项目

引入Mybatis依赖及配置

引入依赖:pom.xml文件

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

添加配置:application.properties

# 指定Mapper的XML文件的位置
mybatis.mapper-locations=class:mapper/*.xml
# 指定实体类所在的包路径
mybatis.type-aliases-package=com.example.testboot.entity

查看此时全部依赖与配置:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.16</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>TestBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>TestBoot</name>
    <description>TestBoot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- web项目启动模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- spring boot项目热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- 工具包,主要简化实体类开发 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>

        <!-- 引入Mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
# 配置项目端口号
server.port=8888

# 配置MySQL数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

# mybatis配置
# 指定Mapper的XML文件的位置
mybatis.mapper-locations=class:mapper/*.xml
# 指定实体类所在的包路径
mybatis.type-aliases-package=com.example.demo.entity
编写接口与XML
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {
    Student getStudent(String name);
}
<?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">

<!-- namespace绑定Dao接口 -->
<mapper namespace="com.example.demo.mapper.StudentMapper">

    <select id="getStudent" resultMap="studentResultMap">
        select * from students where name = #{name};
    </select>

    <!-- 自定义Student实体类封装规则,id:唯一id,方便引用,type:自定义规则的Java类型 -->
    <resultMap id="studentResultMap" type="Student">
        <!-- column:指定哪一列,property:指定对应的javaBean属性 -->
        <id property="id" column="id"/>
        <!-- 定义普通封装规则 -->
        <result property="sex" column="gender"/>
    </resultMap>
</mapper>
编写sevice、controller
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student getStudent(String name) {
        Student student = studentMapper.getStudent(name);
        return student;
    }
}
@RestController // @Controller+@ResponseBody,就不能返回jsp,html页面
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/getStudent")
    public Student getStudent(@RequestParam(value = "name") String name) {
        return studentService.getStudent(name);
    }
}

访问:http://localhost:8888/student/getStudent?name=张三

五、接口文档生成

引入Swagger依赖
        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

swagger2中3.0.0之前的版本需要引入两个依赖:springfox-swagger2及springfox-swagger-ui,版本需要一致2.x.x

添加配置信息
# 解决Spring Boot与Swagger2版本冲突
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
编写配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration  // 配置类
public class SwaggerConfig {

    // 创建API应用
    private ApiInfo webApiInfo() {
        return new ApiInfoBuilder()
                .title("网站-API文档")
                .description("本文档描述了基本接口定义")
                .contact(new Contact("hhh study", "swagger.example", "xxxxxxxx@qq.com"))
                .version("3.0")
                .build();
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(webApiInfo())
                .select()
                .paths(PathSelectors.regex("/student/.*"))
                .build();
    }
}

swagger2中3.0.0之前的版本需要再加一个注解:@EnableSwagger2 开启swagger操作

访问swagger2

访问:http://localhost:8888/swagger-ui/index.html

swagger2中3.0.0之前的版本访问:http://localhost:8888/swagger-ui.html

六、上传GitHub

git status查看状态; -> git add .将所有文件添加到暂存区 -> git commit -m "study"提交;

因为当前在clone下的dev分支上,所以再输入:git push origin dev,将本地修改的dev发送到远程dev。

将远程仓库与本地仓库进行同步:git pull origin main

如果错误fatal: refusing to merge unrelated histories:git pull origin main --allow-unrelated-histories。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值