xl_echo编辑整理,欢迎转载,转载请声明文章来源。更多IT、编程案例、资料请联系QQ:1280023003 百战不败,依不自称常胜,百败不颓,依能奋力前行。——这才是真正的堪称强大!
Spring Boot相对于Spring其他框架,最大的好处在于它不需要很多的配置文件。入门能够更快,而且开箱即用,没有diamante生成,也不需要xml配置。当然它不是增强了Spring而是提供了一种快速使用Spring的方式。在使用Spring的时候,一大堆的xml文件确实不易于开发和维护,要是使用的插件较多,那么可能配置文件都能把你绕晕。所以这也是我喜欢这个款家的原因。
应朋友之邀,出一个Spring Boot的小案例。这个案例主要用于实现Spring Boot框架的基本使用,实现热部署和一个简单的Hello Spring Boot。
第一步:创建工程 注意:创建工程的时候打jar包即可,即使是开发web服务,也可以。不是不需要tomcat服务支持,而是它内部就已经内置了tomcat
第二步:加入依赖
<properties> <java.version>1.7</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>第三步:创建程序入口类(引导类)
package com.echo.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 启动类 * @author Administrator * */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }启动之后可以看到这个图标,没有报错,程序一直运行就证明基本配置没有问题
第四步:编写一个简单的Hello Spring Boot
package com.echo.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloSpringBoot { @RequestMapping("/info") public String info(){ return "Hello Spring Boot"; } }启动引导类,在浏览器访问:http://localhost:8080/info 出现这个界面就证明已经成功了
第五步:解决端口冲突问题(很多程序都会使用8080端口,所以我们需要更改运行端口)创建一个属性文件 application.properties(这个文件名是固定的),加入以下语句即可
server.port=10081 url=https://blog.csdn.net/xlecho第六步:读取属性文件中的值
package com.echo.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloSpringBoot { //读取属性文件中的值 @Autowired private Environment env; @RequestMapping("/info") public String info(){ return "Hello Spring Boot~~~~~~~~~~" + env.getProperty("url"); } }注意:Spring Boot更改了属性文件不需要每次启动引导类,加入热部署即可。
第六步:加入热部署,方便每次更改代码之后直接访问(在pom.xml中加入以下依赖即可)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>