最近项目中需要使用Spring来开发具有restful风格url的后台应用。于是我就想到了使用SpringBoot进行快速的构建和发布。不浪费时间了,下面就直接切入主题。
主要参考:1、使用IDEA创建Maven项目
2、修改pom.xml
4.0.0 com.baron spring-boot-test 0.1 alimaven aliyun maven http://maven.aliyun.com/nexus/content/groups/public// org.springframework.boot spring-boot-starter-parent 1.4.2.RELEASE org.springframework.boot spring-boot-starter-web 1.8 org.springframework.boot spring-boot-maven-plugin maven-failsafe-plugin integration-test verify
输入完成之后,右键重新导入maven依赖
3、编写代码
Application.java // 用于启动应用
import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;// 注解表示了这是一个SpringBoot的Application// 这个在我们进行打包的时候会使用到,因为我们使用spring-boot-maven-plugin打成可执行jar包的时候,// jar包的Main Class并不是我们的Application,所以加上这个注解便于Spring找到需要启动的应用// 你也可以测试是否可以在一个jar包内使用SpringBootApplication,从而启动多个SpringBoot应用@SpringBootApplication// 虽然@SpringBootApplication注解相当于@Configuration, @EnableAutoConfiguration 和 @ComponentScan// 但是需要注意,是相当于没有参数的@ComponentScan,没有参数就只会在和Application类的同级目录下寻找// Spring的Bean,所以我们这边添加上参数"com.*",就会把com目录下所有的类都扫描一遍@ComponentScan("com.*")public class Application { public static void main(String[] args) { // 启动 SpringApplication.run(Application.class, args); } // 用于配置SpringBoot启动时候的参数 // 这个还是比较有用的 @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return container -> { // 配置内部的tomcat容器的监听端口 container.setPort(80); // 配置SpringBoot项目的根路径 container.setContextPath("/hello"); }; }}
HelloController.java 用于对外提供服务
// 此处和Application.java处于不同的包package com.baron.controller;import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;import org.springframework.context.annotation.Bean;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;// RestConroller注解的作用就是专门给restful的服务的Controller使用// 使用此注解解释的类,内部所有提供服务的类的返回值都会被自动解析成json@RestControllerpublic class HelloController { @RequestMapping(value = "/", method = RequestMethod.GET) public String sayHello() { return "Hello, SpringBoot"; }}
4、Maven打包成可执行Jar
Tips:此处假设maven安装成功 直接在cmd输入mvn clean package即可,会自动把所有的依赖都添加进去。