spring boot框架开发入门实战(一)HelloWorld

环境

软件安装

JDK(1.8)

IDEA community(2022)

maven(3.9) Maven – Download Apache Maven zip版即可

mariadb MariaDB Products & Tools Downloads | MariaDB

Navicat

环境变量

JAVA_HOME,jdk安装路径

M2_HOME,maven的安装路径(解压路径)

MAVEN_HOME,与M2_HOME一致;

PATH,添加%JAVA_HOME%/bin;%MAVEN_HOME%/bin;

软件设置
maven
  • 换源

在用户主目录下进入.m2目录,创建一个settings.xml配置文件,内容如下:

<settings>
    <mirrors>
        <mirror>
            <id>aliyun</id>
            <name>aliyun</name>
            <mirrorOf>central</mirrorOf>
            <!-- 国内推荐阿里云的Maven镜像 -->
            <url>https://maven.aliyun.com/repository/central</url>
        </mirror>
    </mirrors>
</settings>
  • 更改本地仓库

在本地创建目录D:\SoftwareData\maven\repository

修改maven安装目录/conf/settings.xml,在下添加

<localRepository>D:\SoftwareData\maven\repository</localRepository>
IDEA

File - Settings - 搜索maven(或展开层级Build,Execution,Deployment > BuildTools > Maven),Maven home directory选项,设置为自己安装的maven路径

小技巧
IDEA快捷键

Alt+Enter:快速生成当前光标所在的标识所需要的import语句。

创建spring boot项目

(参考:https://baijiahao.baidu.com/s?id=1609673298658938529&wfr=spider&for=pc)

版本说明

spring boot,目前有2.x.x和3.x.x,版本号后面的英文代表什么含义呢?

具体含义

  • SNAPSHOT:快照版,表示开发版本,随时可能修改;

  • M1(Mn):M是milestone的缩写,也就是里程碑版本;

  • RC1(RCn):RC是release candidates的缩写,也就是发布预览版;

  • Release或空:正式版,也可能没有任何后缀也表示正式版;

使用网站创建

网址:https://start.spring.io/

sprint boot版本:选择2.7.9(3.0以上需要jdk17

java版本:8

Dependencies选择Spring Web、Lombok、MyBatis Framework

点击GENERATE,自动生成和下载初始化包。

(这里我创建了com.jx.uam工程)

使用IDEA创建
社区版

社区版不支持initializr,需要用破解版。

或者社区版先创建maven项目,再转成 Spring boot。

  • pom中添加parent
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.9</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
  • pom中添加依赖
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
正式(pojie)版

在新建项目时,直接选spring boot initializr。

文件说明
  • pom.xml => Maven的构建文件,里面有关于组建的引用信息

  • src/main/java => 项目的源码类都在此目录下

  • xxxxApplication.java => 其中前半部分为包名,后半部分为项目的启动文件

  • src/main/resources => 项目的资源文件目录

  • src/main/resources/application.properties => 空的属性配置文件

编写helloworld

代码实战

在com.jx.uam下,创建helloworld目录,并在该目录下创建HelloWorld.java文件。

package com.jx.uam.helloworld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class HelloWorld {
    @RequestMapping("/test/sayhi")
    public String sayhi(){
        return "Hello, this is UAM!";
    }
}
编译运行
IDEA中运行

选中你java文件所在的package单击右键选中Mark Directory as,然后选中Sources Root。

此时,xxxApplication.java中即可出现绿色的运行按钮。

首次建议先用mvn命令运行,下载相关依赖包。

命令行运行

在pom.xml所在的目录下,在命令行中运行

mvn clean package
java -jar ./target/xxxx.jar

(如有问题,请参考“问题汇总”)

通过浏览器或postman

调用url

http://127.0.0.1:8080/test/sayhi

可以得到结果:

Hello, this is UAM!
进阶使用
传入参数返回JSON

在HelloWorld的class代码中添加

    @RequestMapping("/test/json")
    public String index(int age, String name){
        return String.format("{'name':%s, 'age':%s}", name, age);
    }

通过postman,调用url

http://127.0.0.1:8080/test/json?age=12&name=mike

可以得到结果:

{'name':mike, 'age':12}
问题汇总
首次mvn clean package报错java.nio.file.AccessDeniedException

解决:

更改默认的mvn repository路径。

首次mvn clean package报错类版本不匹配
[INFO] Finished at: 2023-03-07T08:22:08+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile (default-compile) on project uam: Compilation failure
[ERROR] /D:/Coding/Java/study/uam/src/main/java/com/jx/uam/helloworld/HelloWorld.java:[3,32] 无法访问org.springframework.boot.SpringApplication
[ERROR]   错误的类文件: D:\SoftwareData\maven\repository\org\springframework\boot\spring-boot\3.0.4\spring-boot-3.0.4.jar(org/springframework/boot/SpringApplication.class)
[ERROR]     类文件具有错误的版本 61.0, 应为 52.0
[ERROR]     请删除该文件或确保该文件位于正确的类路径子目录中。
[ERROR]
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]

原因:boot 3.0.0版本要求jdk17以上,自己的版本是jdk8

解决:改用17版本以上的jdk

mvn clean package偶尔会卡住

ctrl+c中断后再次运行

IDEA对于import导入的模块总是报错 “Cannot resolve symbol”

情况一:未引用有效的JDK

处理方案:File - Project Structure - Project SDK,看看SDK有没有选,重选一个本地的自己安装的jdk。

情况二:无有效的Maven设置

处理方案:File - Settings - 搜索maven(或展开层级Build,Execution,Deployment > BuildTools > Maven),Maven home directory选项,设置为自己安装的maven路径

mvn编译时报Test异常
[INFO] 
[INFO] Results:
[INFO]
[ERROR] Errors: 
[ERROR]   UamApplicationTests.contextLoads ? IllegalState Failed to load ApplicationCont...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

原因:测试的方法有错导致整体打包时抛出异常。

解决:避免 maven 项目打包时受到 test 方法影响。

在pom.xml中,添加如下配置:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.22.2</version>
	<configuration>
		<skipTests>true</skipTests> <!-- 不会编译测试 -->
	</configuration>

或者

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.22.2</version>
	<configuration>
		<testFailureIgnore>true</testFailureIgnore> <!-- 忽略测试执行期间发生的任何故障 -->
	</configuration>
</plugin>
首次java -jar ./target/xxx.jar启动运行报错
***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
        If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
        If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).


原因:springboot自动配置时,检测到了MySQL、Mybatis等和数据库相关的依赖包,但我们的配置文件中却没有添加相关的数据库配置。

解决办法:

  • 如果没有用到数据库,先把pom.xml中的数据库依赖去掉
  • 在application.properties/yml中添加数据库相关配置。
  • 在 SpringBoot 应用程序启动时,排除 jdbc 的自动装配机制即可,在程序入口文件中新增配置注解 “ exclude=DataSourceAutoConfiguration.class ”
@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
public class UamApplication {

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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值