前言:
想了很久用docker搭建一个java开发环境。其实java的环境上手非常简单,只需一JDK就可以开始快乐的玩耍了。那么今天被困到成都火车站的我就来更新下博客。
一:拉取镜像并完善系统工具
既然是使用docker 那么我们先拉一个centos系统打底(为什么是centos?其实随便什么发行版都行。)
docker pull centos

镜像下载成功后,就去生成一个容器,到容器里面去搞点事情
#启动一个容器 将宿主机的99端口映射到容器的8080端口
#将宿主机的一个文件映射到 容器的根目录
docker run -it -p 99:8080 -v ~/Program/code/private:/private centos:latest
先装点vim curl 等工具
yum install curl vim
二:安装JDK&Maven
我们直接选择简单的yum 安装。yum镜像库里面有很丰富的镜像,java这种热门语言必然是有的
yum install java-1.8.0-openjdk
我们选择的是openJDK 1.8 版本。 (垃圾oracle!!!!)
傻瓜式安装完成后

接下来安装Maven
yum install maven

三:初始化spring boot

选择Spring Initializr 创建

填写一些项目初始化的参数

由于只做演示,我就只选择一个web就行了(在开发中按照自己的需求来)

修改项目存放的地址到我们之前映射到容器里面的地址

点击完成后,ide会帮我们下载包并解压,引入maven 一气呵成

然后我们就得到了一个spring boot项目了。
四:编写一个控制器
我们去编写一个简单的控制器。来完成一个hello world 的功能

package com.kbz.java.javahello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//加上controller注解
@Controller
@SpringBootApplication
public class JavaHelloApplication {
public static void main(String[] args) {
SpringApplication.run(JavaHelloApplication.class, args);
}
@ResponseBody
//注册路由
@RequestMapping("hello")
public String hello(){
return "hello spring boot";
}
}
代码写好了之后,由于我们之前使用了映射文件到容器。所以我们直接可以去容器中启动我们的项目了
mvn spring-boot:run

中途下载了很多东西,比如Tomcat之类的,这些细节我们不用管。Sping boot 的理念就是开箱即用
上图中我们可以看到,spring boot帮我们在8080起了一个web服务
我们可以在容器中使用curl 去请求 localhost:8080/hello 也可以在宿主机用浏览器请求 localhost:99/hello (这里因为在创建容器的时候将容器的8080映射到宿主机的99上了)

好了。今天的介绍就到这里了。内容很基础,大神见笑。如有错误欢迎提出,大家共同学习。感谢!
网友评论