1、组件添加
1. @Configuration
-
基本使用
- 告诉Spring Boot这是一个配置类,其作用 == 配置文件
- 配置类也是一个组件,配置类中使用@Bean标注在方法上给容器注册组件 -
Full模式与Lite模式
- 配置类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
2. @Bean、@Component、@Controller、@Service、@Repository
给容器中注册组件的方式:
1)包扫描+组件标注注解(@Controller / @Service / @Repository / @Component)
缺点:局限于自己写的类
2)@Bean【导入的第三方包里面的组件】
- 配置类里使用@Bean标注在方法上给容器注册组件,默认也是单实例的
- 给容器中添加组件,以方法名作为组件ID,返回类型就是组件类型,返回的值就是组件在容器中的实例。
- @Bean(“tom”) //组件名默认为方法名,可通过这种方式自定义组件名
3. @ComponentScan、@lmport
@Import【快速给容器中导入一个组件】
用法:
@Import({User.class, DBHelper.class})
——给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
高级用法:
@Import({MyImportSelector.class})
详见 补充 - @Import的高级用法
ImportSelector:返回需要导入的组件的全类名数组
4. @Conditional
条件装配:满足Conditional指定的条件,则进行组件注入
2、原生配置文件引入
@ImportResource
使用场景:已有XML配置文件,且未导入进容器
用法:在配置类下添加 @ImportResource(“classpath:beans.xml”)
3、配置绑定
使用Java读取到 properties文件 中的内容,并把它封装到JavaBean中,以供随时使用。
原始方法:
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean。
}
}
}
1、@Component+@ConfigurationProperties
这两个注释需要在实体类中写,因为只有在容器中的组件才会拥有SpringBoot提供的强大功能。
/*
*/
//将该组件加入到容器中
@Component
//将该类与配置文件中的"mycar"属性绑定
@ConfigurationProperties(prefix = "mycar")
public class Car {
private String brand;
private Integer price;
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", 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;
}
public Car(String brand, Integer price) {
this.brand = brand;
this.price = price;
}
public Car() {
}
}
2、@EnableConfigurationProperties + @ConfigurationProperties
在配置类中写
3、@Component + @ConfigurationProperties
在配置类中写
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}