为啥要学习springboot呢?因为spring,springmvc麻烦!没错,springboot带给项目的就是便利,轻盈,一点都不累赘.
来创建第一个springboot项目,参考网址:https://qbgbook.gitbooks.io/spring-boot-reference-guide-zh/
我使用的是maven来管理项目的,在pom.xml下添加这两个依赖包
第一个parent包,其version指定的版本号就是你当前创建的springboot的中所用的spring包的版本号,比如spring-boot-start,spring-context,spring-aop,beans,core等等
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
第二个依赖包,是针对springboot的web项目导入的,在parent中不包含有该依赖包,需要自己手动导入,就是我们常用的springmvc所用的依赖包,包括tomcat的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
因为使用maven来打包的
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
设置完以上三个依赖就可以写一个springboot的web项目了
操作非常简单,设置一个controller
@RestController
public class TestController2 {@RequestMapping("/greeting")
public @ResponseBody String hello() {
return "你好!世界!";
}
因为springboot不用把项目打包成war包,将其发布在tomcat上运行,它是直接以jar包的形式运行
这需要一个启动类,入口就是静态方法main
@SpringBootApplication(scanBasePackages="com.xxx.controller")
public class MyApplication{public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
直接执行 run as--->java Application,出现以下结果,表示你执行成功了
在启动类上有一个注解,@SpringBootApplication(scanBasePackages="com.xxxx.controller"),SpringBootApplication这个注解包括了以下的注解功能
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration //springboot的配置扫描,即使用@Configuration注解的类,在启动时会被加载进来
@EnableAutoConfiguration //springboot的自动装配扫描,比如@RestController这个注解
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
scanBasePackages="com.xxxx.controller"表示的是要加载的是那个包下的自动装配类
在写springboot的时候,还遇到一个问题,那就springboot默认使用的tomcat的版本是8.x的,但我想用tomcat7.x的,加入以下依赖,就可以把tomcat的版本改掉
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>${tomcat.version}</version>
</dependency><properties>
<tomcat.version>7.0.85</tomcat.version>
</properties>