SpringBoot - @ImportResource,@ConfigurationProperties 让xml生效与类属性绑定配置文件

@ImportResource

作用:使用.xml配置文件

范围:必须使用在主程序@SpringBootApplication或配置类上@Configuration

@SpringBootApplication
@ImportResource("classpath:application.xml")
public class Learn20221218Application {
    public static void main(String[] args) {
        SpringApplication.run(Learn20221218Application.class, args);
    }
}

@ConfigurationProperties

作用:能够实现Bean的按需配置

范围:类上,方法上

参数:prefix与value prefix=value

@ConfigurationProperties 不能把类注入到容器当中,所有要使用时使用@Component把类注入到容器当中,或者选择其它方式进行注入

并且被@ConfigurationProperties修饰的类中的属性 需重写Get与Set方法

@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@EnableConfigurationProperties

作用:如果被@ConfigurationProperties的类没有被@Component修饰的话 可以使用此类加载到IOC容器当中

范围:被@Configuration修饰的配置类上

参数:exclude数据类型 Class[],excludeName数据类型String[] xxx类.Class.getName()

@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
public class HelloServiceAutoConfiguration {

}
@ConfigurationProperties(prefix = "service.config")
public class HelloServiceProperties {

}

 

posted on 2022-12-20 18:08  Mikasa-Ackerman  阅读(98)  评论(0编辑  收藏  举报

导航