SpringBoot简单使用

前言

初步探索springboot使用方法,并搭建一个简单的springboot应用

准备

这里我用的ide工具为eclipse-oxygen版本,jkd1.8maven3.6.0版本。
在这里,个人推荐java新手使用eclipse进行开发工作,intellij idea这类工具太过于强大,不利于新手学习。
java环境变量配置以及eclipse如何集成maven,配置开发环境可自行百度。
关于maven,需要配置一下setting.xml文件,将镜像地址配置为国内地址,多数文章推荐阿里云,我在这里也是用的阿里云的镜像:

<mirror>    
<id>alimaven</id>    
<mirrorOf>central</mirrorOf>    
<name>aliyun maven</name>    
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>  
</mirror>  

但是我本人在公司用的公司无线网,下载jar包速度极慢,具体原因未知。幸好本地仓库之前下载的有springboot核心jar包:)

开始

1.首先打开eclipse,新建一个工作空间~

2.新建一个maven项目

SpringBoot简单使用

3.建好后打开pom.xml文件,添加以下代码:

	<!-- 统一版本控制 -->
		<parent>
		
		<groupId>org.springframework.boot</groupId>
		
		<artifactId>spring-boot-starter-parent</artifactId>
		
		<version>1.4.0.RELEASE</version>
		
		<relativePath/> <!-- lookup parent from repository -->
		
		</parent>
	<dependencies>

		<!-- spring boot 核心 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <scope>test</scope>
		    <version>4.12</version>
		</dependency>

	</dependencies>

笔者看网上好多文章依赖了springboot 其他依赖,其实只用依赖一个核心包,就可以启动项目啦!
添加好后,保存。右键项目选择maven—update project,勾选force update of snapshots/releases,ok。
maven就会自动去阿里云仓库或本地仓库找到对应的jar包,并下载下来了

ps:我是因为依赖其他包失败才这样做的。。。

这里parent版本控制是一定要依赖的,主要可以根据版本号去仓库找到对应的子jar包。spring-boot-starter-web也必不可少,这是springboot的核心包。至于junit这是一个测试用的,可有可无,以防maven将springboot项目构建好后,test类抛错,这里导入了junit4.12版本。

注意事项

若maven在下载资源时出错,导致jar未下载下来,可以到本地仓库路径下,找到所有.lastupdated后缀文件,删除之,重新update maven项目。我遇到的pom.xml文件第一行抛错就是这样解决的!
默认的本地仓库路径是:${user.home}/.m2/repesitory 可以再settings.xml中自定义:

<localRepository>D:\maven\MavenBox</localRepository>

SpringBoot简单使用
eclipse 中maven配置如下:
SpringBoot简单使用
注意global settings需要为空,不然自定义本地存放地址无效。。。

4.新增启动类

打开项目中App.java,在类名上方添加以下配置:

@Controller
@EnableAutoConfiguration

这里@Controller将该类添加控制
关于@EnableAutoConfiguration 的作用可以参考文章 SpringBoot之@EnableAutoConfiguration注解.

最后添加代码:

package com.csii.electrinicsport;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;

@Controller
@EnableAutoConfiguration
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}

右键run,就可以运行springboot项目啦
SpringBoot简单使用
到这里,一个springboot 基于Maven的项目就搭建好了,下面我们来测试一下,在App.java类中,添加构造方法:

	@RequestMapping
	@ResponseBody
	public String App(){
		System.out.println("*************into App.java***********");
		return "成功访问Springboot项目!";
	}

接着重启项目,这里说一下,可以在项目中新增resources/application.properties文件,里面可以自定义端口、根路径等,否则默认端口为8080,默认根路径为/
打开浏览器访问:http://localhost:8080,即可看到:
SpringBoot简单使用
控制台输出:
SpringBoot简单使用

结语

到这里,一个简单的springboot项目我们就搭建好了,之后还会会根据springboot项目整合一个微信小程序练习。

to be continue…