SpringBoot入门
创建一个SpringBoot项目:File-New-Project,点击图中左侧的Spring Initializr,后面只需填写项目名等信息即可。
创建后,会自动生产一个SpringBoot项目的启动类:
@SpringBootApplication
public class SpringbootDemo01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo01Application.class, args);
}
}
SpringBoot的自动装配过程跟注解@SpringBootApplication密切相关,如果导入了相关的依赖包,相应的配置将有SpringBoot自动完成,比如导入了SpringMVC相关的jar包,Disp-atcherServlet和视图解析器将由SpringBoot配置,无需开发者手动配置。
pom.xml文件中有一个父工程:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
另外还用两个依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
第一个依赖是Web项目相关的(因为创建的时候勾选了SpringWeb),导入了SpringMVC相关的jar包,第二个依赖是测试相关的。一般还有一个依赖(spring-boot-starter),但是因为之前选择了SpringWeb,可能在pom文件中不是必须的,该依赖是:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
yaml配置入门
SpringBoot项目创建后会自动生产一个空的配置文件:application.properties,但SpringBoot推荐使用yaml进行配置,yaml语法简单,且可以方便地配置数组、集合、对象等复杂值。加入存在实体类Person如下:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
private String name;
private int age;
private boolean isHappy;
private List<Integer> list;
private Map<String, String> map;
private Dog dog;
}
yaml配置如下:
server:
port: 8031
person:
name:
xxx
age:
10
isHappy:
false
list:
- 2
- 5
- 7
map:
k1: v1
k2: v2
dog:
name: 旺财
age: 3
那么输入person对象结果为:Person(name=xxx, age=10, isHappy=false, list=[2, 5, 7], map={k1=v1, k2=v2}, dog=Dog(name=旺财, age=3)),即yaml中的相应配置全部注入到person对象的属性中去。@ConfigurationProperty中的prefix属性表示获取yaml配置文件中的对象名(此处为person),而yaml语法中对空格要求比较严格,一个根对象位于一行的开始,前面无空格,如果有空格,说明该行是其中的某个属性。yaml的k-v键值对中间的冒号后面必须空一格,数组的各个值前必须有-,并且-后还有一空格。
注意该yaml文件名为application.yaml,一般不可改为其他名字,这也是SpringBoot的约定大于配置的体现。如果非要改,那么就要在实体类上加上注解@PropertySource(value = "classpath:配置文件名")。上述yaml配置中还修改了tomcat的端口,一般为8080,这里修改为8081。
yaml中还支持EL表达式的形式:
person:
name:
xxx${random.uuid}
age:
${random.int}
isHappy:
false
list:
- 2
- 5
- 7
map:
k1: v1
k2: v2
dog:
name: ${person.hello:hello}_wangcai
age: 3
上述yaml文件中,名字后面跟了一个uuid,年龄为一个随机整数,如果person的hello属性有值,则dog的名称也为hello属性的值,否则为hello,运行结果为:Person(name=xxx10372281-125d-492f-9a43-4af7c362d928, age=-635582644, isHappy=false, list=[2, 5, 7], map={k1=v1, k2=v2}, dog=Dog(name=hello_wangcai, age=3))