摘要:让Spring应用从配置到运行更加快速,演示DIY Spring Boot框架时,如何配置端口号,如何添加日志。
Spring Boot 框架帮助开发者更容易地创建基于Spring的应用程序和服务,使得开发者能够快速地获得所需要的Spring功能。提供了非功能性的大型项目类特性,如(如内嵌服务器、安全、度量、健康检查、外部化配置),内部封装了tomcat的一些核心jar包,将发布封装了,因此不需要将项目(war包)发布到外部tomcat上。
可以在Spring Boot官网 https://start.spring.io/ 快速构建项目,这个简单易用,而且会自动生成启动类。本文重点介绍如何使用Eclipse构建。
搭建一个简单的、基于Restfull 风格的Spring web mvc 项目,结构如下:
环境:
eclipse:Oxygen Release (4.7.0);java version :"1.8.0_77";
maven:3.5.4;Servlet3容器(tomcat)
1. 配置maven的settings.xml
配置文件中加入了阿里巴巴的镜像。
E:/MyLibs alimaven-central central aliyun maven http://maven.aliyun.com/nexus/content/repositories/central/ jboss-public-repository-group central JBoss Public Repository Group http://repository.jboss.org/nexus/content/groups/public
2. Eclipse配置Maven
Maven配置如下图所示,如果已经配置,可以忽略此步。
3. 创建maven项目
new-->other-->maven-->Maven Project-->next-->finsh,maven项目就建好了。
包名和项目名根据需求自定义。
4. 配置pom文件
4.0.0 org.springframework.boot spring-boot-starter-parent1.4.0.RELEASE com.spring.boot TestWebApp0.0.1-SNAPSHOT jar TestWebApp http://maven.apache.org UTF-8 junit junittest org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-loggingorg.springframework.boot spring-boot-starter-log4j2org.springframework.boot spring-boot-maven-plugin
5. 添加日志
项目使用了log4j2打印日志。首先,在src/main目录下新增文件夹resources,然后,在resources下创建log4j2.xml。这个日志配置比较简单,有待优化。
6. 设置端口号
在resources下创建application.properties。
1. 编写测试代码
javaBean定义如下,包括用户ID和用户名。
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 7797704227043955944L;
private Long id;
private String name;
// getter/setter omitted
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
控制器代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
private static Logger logger = LoggerFactory.getLogger(UserController.class);
@RequestMapping("/{id}")
public User view(@PathVariable("id") Long id) {
logger.info("接收的请求参数 begin --- id = {}", id);
User user = new User();
user.setId(id);
user.setName("Spring Boot");
return user;
}
}
通过在UserController中加上@RequestMapping 配置请求路径。通过在main方法中运行SpringApplication.run()来启动项目:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
这时候项目就可以运行了,在Application 中run as-->java application 。控制台打印结果:
截图中红色方框圈中的文字说明了系统启动成功,而且,端口号是8080。此时在浏览器输入http://localhost:8080/user/100即可看到页面效果:
控制台打印结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



