SpringBoot入门

xiaoxiao2021-02-28  133

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

Spring Boot化繁为简,简化配置,微服务的入门级微框架,spring的微服务是springcloud。

Spring Boot特点: 1. 创建独立的Spring应用程序 2. 嵌入的Tomcat,无需部署WAR文件 3. 简化Maven配置 4. 自动配置Spring 5. 提供生产就绪型功能,如指标,健康检查和外部配置 6. 绝对没有代码生成和对XML没有要求配置[1]

准备环境

jdk1.8 intellij idea 2016.3.1

Hello例子

新建工程-》Spring Initializr-》点next-》选web-》选工程位置后点finish。 新生成的包下有:

@SpringBootApplication public class GirlApplication { public static void main(String[] args) { SpringApplication.run(GirlApplication.class, args); } }

这是应用启动入口,@SpringBootApplication表示这是一个SpringBoot的应用。现在直接运行当然什么都看不到。

加controller

@RestController public class HelloController { @RequestMapping(value = "/hello",method = RequestMethod.GET) public String say(){ return "say hello to spring boot "; } }

@RestController标注这是控制器,RequestMapping设置访问路径和访问方式(这里是GET方式) 现在你可以通过localhost:8080/hello来访问了。

设置配置文件

编辑resources下的application.properties文件,加入如下:

server.port=8082 server.context-path=/girl

再次访问的链接就变成了localhost:8080/girl/hello

我们继续来加点东西,

cupSize=B

在HelloController 中通过注解获取配置的值

@Value("${cupSize}") private String cupSize;

也可用yml格式的配置文件,相比properties更直观,一目了然,例:

application.properties server.port=8082 server.context-path=/girl application.yml server: port: 8060 context-path: /girl

配置文件中定义的变量获取配置文件中已定义变量的值:

cupSize: B age: 16 content: "cupSize: ${cupSize},age: ${age}"

通过配置获取对象

配置文件中 girl: cupSize: B age: 16 content: "cupSize: ${cupSize},age: ${age}" Bean定义: @Component @ConfigurationProperties(prefix = "girl") public class GirlProperties { private String cupSize; private Integer age; private String content; public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } HelloController中使用: @Autowired private GirlProperties girlProperties;

运行方式

1、通过ide运行,没什么可说的

2、cmd工程目录下 mvn spring-boot:run

3、cmd工程目录下 先mvn install 再java -jar girl-0.0.1-SNAPSHOT.jar

开发环境与生产环境

新建application-dev.yml,和application-dev.yml,修改application.yml,其内容:

spring: profiles: active: dev

然后通过运行方式的第三种:第一步一样,第二步变为 java -jar girl-0.0.1-SNAPSHOT.jar –spring.profiles.active=prod

源码

Spring Boot基础

转载请注明原文地址: https://www.6miu.com/read-20200.html

最新回复(0)