基于maven,首先看pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<!-- springboot启动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springboot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
相关插件配置,这一项可以不配置也行
<plugins>
<!-- 项目编译 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 打包跳过测试代码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<!-- 打包项目源码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
新建Application类,启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller类
@RestController
public class HelloController{
@RequestMapping("/hello")
public String hello(){
System.out.println("hello");
return "ok";
}
}
直接在applicaotion右键 run 启动运行即可
即可完成springboot快速搭建,
springboot默认会读取classpath下的application.properties或者是application.yml 文件,在这个文件中我们可以定义需要我们想要的配置,如:我们想把port改为8888
application.yml
server:
port: 8888
关于入口类和@SpringApplication
springboot通常会有一个名字为*Application的类(1.4版本以下可能没有),入口类里有一个main方法,这个main方法其实是一个标准的Java应用的入口方法,在main方法中使用SpringApplication.run,启动SpringBoot项目。
@SpringBootApplication是SpringBoot的核心注解,它是一个组合注解,源代码如下:
@SpringBootApplication注解主要组合了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan;如果不使用这个组合类,在启动类上加上这三个注解也是可以的。
其中这几个注解的作用:
@EnableAutoConfiguration让SpringBoot根据类路径中的jar包依赖为当前项目进行自动配置。
例如:添加spring-boot-starter-web依赖,会自动添加Tomcat和SpringMvc的依赖,那么springboot就会对Tomcat和springMvc进行自动配置。
又如:添加了spring-boot-starter-data-jpa依赖,springboot会自动进行jpa相关配置。springboot会自动扫描@SpringBootApplication所在类的同级包,以及下级包里的Bean(如果是jpa项目还会扫描标注为@Entity的实体类)。建议入口类放在包平行位置。
ok