- 主启动类详解
package com.bill;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
- 1.SpringApplication(引用自狂神说)
这个类主要做了以下四件事情:
1、推断应用的类型是普通的项目还是Web项目
2、查找并加载所有可用初始化器 , 设置到initializers属性中
3、找出所有的应用程序监听器,设置到listeners属性中
4、推断并设置main方法的定义类,找到运行的主类
- 类的构造方法
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
// ......
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.setInitializers(this.getSpringFactoriesInstances();
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}
- run方法调用关系图(引用自狂神说)
- springboot配置
- application.yaml语法格式
# k=v
# 对空格的要求十分高
# 普通的key-value
# 可以注入到配置类中
#
name: bill
# 对象
student0:
name: bill
age: 4
student1: {name: bill,age: 6}
# 数组
pets0:
- dog
- cat
- fish
pets1: [dog,cat,fish]
-
举例说明通过yaml配置文件,可以给配置类注入参数
-
新建一个dog类,通过添加注解@Component将dog类变成一个组件;通过添加@Value注解给属性赋值
package com.bill;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Auther: wangchunwen
* @Date: 2023/1/14 - 01 - 14 - 21:08
* @Description: com.bill
* @version: 1.0
*/
@Component
public class Dog {
@Value("lulu")
private String name;
@Value("1")
private Integer age;
public Dog(){
}
public Dog(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 测试类,通过@Autowired注解,自动注入dog实例,无需new一个对象;直接将实例dog打印
package com.bill;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootApplicationTests {
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
}
运行结果:
标签:SpringBoot,age,dog,50,230114,org,import,public,name From: https://www.cnblogs.com/wcwblog/p/17052601.html