springBoot并不是一个新的框架,而是提供一个能快速开发spring项目的一种方式,使用springboot不需要进行繁琐的配置和部署到tomcat之类的服务器上,只要运行一个几行代码的main方法即可以快速的运行项目。使用springboot可以快速的整合开发项目,适合于开发微服务。
1.新建maven工程,在pom.xml文件中添加依赖
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.新建一个Application.java文件
package base;
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// same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
@SpringBootApplication注解相当于 @Configuration @EnableAutoConfiguration @ComponentScan这三个注解,他们的作用分别是:
@Configuration
它就是JavaConfig形式的Spring,Ioc容器的配置类使用的那个@Configuration,使用@configuration可以不适用xml的方式,通过类来对bean进行配置。
@ComponentScan
这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。 我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。
@EnableAutoConfiguration
@EnableAutoConfiguration: 启用springboot的自动配置机制,可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器
3.新建application.properties文件,application文件用于对springboot进行配置
#配置端口,可以选择不配,默认为8080
server.port=8085
4.运行Application.java的main方法即可启动springboot,无需部署服务器,控制台成功输出以下信息即启动成功
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)
.....
.....
2018-06-25 17:00:51.739 INFO 24524 --- [ main] base.Application : Started Application in 9.486 seconds (JVM running for 13.768)
5.编写controller
新建example类,在浏览器访问http://localhost:8085/hello就可以看到返回hello world
@RestController
public class Example {
@RequestMapping("/hello")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}