创建一个Maven(maven-archetype-quickstart)项目,在pom.xml文件配置Spring Boot 依赖
配置与<properties 同级的文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
配置与<dependency 平级的文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置与<dependencies 同级的文件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
配置完成之后保存文件,会自动下载相关jar包
然后在项目文件夹下创建class类,写入功能代码(这里是做openlayer模拟报警的一个功能测试,该类返回一个json数据格式的经纬度,根据需求放入相关的功能代码)
package simple.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@RestController 标注是一个Controller类 并且支持json数据格式输出
@RestController
public class waner {
@RequestMapping("/warninfo")
public String warenInfo() {
double x = Math.random() * 2 + 115;
double y = Math.random() * 2 + 39;
String str = "{\"lon\":" + x + ",\"lat\":" + y +"}";
return str;
}
}
这里需要创建一个CorsConfig.java文件,解决跨域问题
package simple.test;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET","POST","DELETE","PUT","PATCH")
.maxAge(3600);
}
}
创建resources文件夹里面放置一个文件,文件名为application.properties,最好不要改动该文件名,在文件配置一个端口
server.port = 8012
下面在主类文件中写入相关代码
package simple.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
//@SpringBootApplication 代表springboot的启动类 用来标注主程序类 说明是一个springboot应用
@SpringBootApplication
public class App extends SpringBootServletInitializer
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
//将springboot应用驱动起来
SpringApplication.run(App.class, args);
}
}