SpringBoot的配置类

配置类用于向容器中注入组件,几乎每个配置类都绑定着一个或多个配置属性类,而配置属性类绑定着一个配置文件。

一、配置类注入Bean的方式

1.@Bean

@Configuration
public class DogConfiguration {
    @Bean
    public Dog dog() {
        Dog dog = new Dog();
        dog.setName("小黑");
        dog.setType("柯基");
        return dog;
    }
}

如果@Bean不指定id,那么id默认为方法名

2.@ComponentScan
通过@Bean方式注入,当要注入的组件过多时会造成代码臃肿,可考虑使用@ComponentScan
此注解默认会扫描同一个包下的所有组件,可传入参数改变默认扫描路径。

@ComponentScan
@Configuration
public class CatConfiguration {

}
@Component
public class Cat {
    private String name;
    private String type;

@Component如果不指定id, 那么id默认为小写类名
主程序类的注解@SpringBootApplication是一个合成注解,里面就包含了@ComponentScan且没有参数,所以主程序默认扫描的包就是它所在的包。

3.@Import

@Import({Dog.class})
@Configuration
public class DogConfiguration {

组件的id为它的全类名

4.@ImportResources

@ImportResource("classpath:beans.xml")
@Configuration
public class CatConfiguration {
<bean id="cat" class="com.rosen.boot.pojo.Cat">
    <property name="name" value="大黄"></property>
    <property name="type" value=""></property>
</bean>

此注解用于兼容Spring,方便Spring项目向SpringBoot过渡。

二、配置属性类

配置属性类中的属性与一个配置文件的属性有着绑定关系。

cat:
  name: 大黄
  type:
@ConfigurationProperties(prefix = "cat")
public class CatProperties {
    private String name;
    private String type;

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
@Configuration
@EnableConfigurationProperties({CatProperties.class})
public class CatConfiguration {
    @Bean
    public Cat cat(CatProperties catProperties) {
        Cat cat = new Cat();
        cat.setName(catProperties.getName());
        cat.setType(catProperties.getType());
        return cat;
    }
}

注:配置类不能使用Spring的自动注入功能,若要使用容器中的组件只有通过传参方式

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值