SpringBoot 入门
SpringBoot入门
SpringBoot来简化spring的应用开发,约定大于配置,just run就能创建一个独立的产品级别的应用
微服务:是一种架构风格,一个应用应该是一组小型服务,这些小型服务可以通过http沟通,每个功能元素都是一个可独立替换和升级的软件单元
不需要配置tomcat,xml等,且运行时只需要打包成jar包用java -jar命令即可本地运行
SpringBoot POM文件分析:
- 父项目:SpringBoot的版本仲裁中心,以后导入依赖默认不需要写版本号
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2.导入的依赖:spring-boot-starter-web导入了web正常运行所需要的组件
SpringBoot将所有应用场景(mail,redit等)都抽取出来,做成一个个启动器starter,只需要导入starter相关场景的依赖都会导入进来
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
主程序类:
@SpringBootApplication:注解用于标注在某个类上说明这个类是主配置类,SpringBoot应该运行这个类的main方法来启动springboot应用,会将该类所在包及子包下的所有类扫描到spring容器中
@ResponseBody:SpirngMVC中的注解,指将数据直接传送给游览器
快速构建Springboot项目:
@RestController: 等于@ResponseBody+@Controller
1.选择Spirng Initializr,并选择URL为阿里云 https://start.aliyun.com/
2.勾选所需要的组件
resources文件夹目录:
- static:保存所有的静态资源:jss css images
- templates:保存所有的模板页面,SpringBoot默认不支持jsp
- application.properties:SpringBoot配置文件
SpringBoot配置
SpringBoot使用一个全局配置文件,配置文件名称固定:
application.properties或者application.yml
YAML:以数据为中心,比json,xml更适合做配置文件
YAML语法:
- 基本语法:
key: value 表示键值对,注意:后有个空格
以空格控制层级属性,只要左对齐就是同一个层级 - 值的写法:
对象:
friends: {lastName: zhangsan,age: 18}
或者
friends:
lastName: zhangsan
age: 18
数组:
pets:
- dog
- cat
- pig
@Component
@ConfigurationProperties(prefix = “person”)
两个注解加在person类之前,将配置文件中配置的每一个属性的值映射到组件(类)中@value也可以实现这个功能,@value一般用于单一值的注入
配置文件提示依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
@PropertySource:加载指定的配置文件,@ConfigurationProperties一般用于全局配置文件,@PropertySource用于指定特定的配置文件比如@PropertySource(value={classpath:person.properties})
@ImportResource:导入spring的配置文件让其生效
SpringBoot使用@bean给容器添加组件:定义一个配置类加上@Configuration注解,并在配置类中添加@bean注解并返回bean容器
定义一个MyAppConfig类
public class MyAppConfig{
@Bean //将方法的返回值添加到容器中,容器中生成的组件名就是helloService1
public HelloService helloService1(){
return new HelloService();
}
}
在多个Profile文件中,在某个Profile加入spring.profiles.active=dev即可选择该配置文件;在yml中则为spring:profile: dev;命令行可以在运行的时候激活运行环境–spring.profiles.active=dev