1、容器功能
1.1、容器添加
1、@Configuration
- 基本使用
告诉springboot这是一个配置类
@Configuration // 告诉SpringBoot这是一个配置类
// @EnableConfigurationProperties(Car.class)
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
//user组件依赖了pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom") // 括号内可以给组件指定其他的名字
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
2、@SpringBootApplication(proxyBeanMethods = true)
- full模式和lite模式
- 使用场景:主要使用于组件之间的依赖关系
- 默认为True(full)
User user01 = run.getBean("user01", User.class);
Pet tom = run.getBean("tom", Pet.class);
System.out.println(user01.getPet()==tom);
现在同时有两个类User,Pet
测试此时的User拥有的pet是否为容器中的pet
1.2、原生配置文件导入
1、@ImportResource(“classpath:beans.xml”)
- 使用场景:
- 部分代码仍然使用的是spring的xml形式来注册bean
- 在springboot的启动项中导入资源
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="haha" class="com.melon.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>
<bean id="hehe" class="com.melon.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>
@ImportResource("classpath:beans.xml")
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);
System.out.println("hehe:"+hehe);
1.3 配置绑定
1、@ConfigurationProperties(prefix = “mycar”)
- prefix:前缀
- 使用场景
- 绑定配置文件,直接修改
- 注意:绑定的时候需要先要将Car注册为组件,不然无法绑定
server.port=8888
mycar.brand=BYD
mycar.price=100000
/*
* 只有在容器中的组件才能享受soringboot的功能
* */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
public Car() {
}
public Car(String brand, Integer price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
@Autowired
Car car;
@RequestMapping("/car")
public Car car(){
return car;
}