springBoot的注解的使用(二)

原生配置文件导入(xml)以及配置绑定

二、原生配置文件导入

@ImportResource

beans.xml


<?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="user01" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="user02" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>
@ImportResource("classpath:beans.xml")
public class MyConfig {}

		// =======测试======
        boolean haha = run.containsBean("haha");
        boolean hehe = run.containsBean("hehe");
        System.out.println("haha:"+haha);//true
        System.out.println("hehe:"+hehe);//true

三、配置绑定

使用情况:

当组件的一些属性需要变动,或者不便于在代码中写死,此时可以将一些属性值写在配置文件中,便于修改。

1、@Component+@ConfigurationProperties

作用:将配置文件中配置的属性绑定到容器中的类中

属性:

​ prefix:配置文件中的前缀

tips:

​ 只有在容器中的组件才能使用配置绑定,所以一般都会同时使用@Component直接


@ConfigurationProperties(prefix = "person")
@Component
@Data
public class Person{
    
    private String name;
    private Integer age;
}

2、@EnableConfigurationProperties+@ConfigurationProperties

@EnableConfigurationProperties:

作用:开启属性配置功能,同时将要开启属性配置功能的组件放入容器中

属性:

​ value:Class类型的,开启哪个类的属性配置功能

使用:

​ 一般标注在配置类上

示例:

@@ConfigurationProperties(prefix = "user")
@Data
class User{
    private String name;
    private Integer age;
}


@EnableCongigurationProperties(USer.class)
//1、开启User配置绑定功能
//2、把USer这个组件自动注册到容器中
@Configuration
class MyConfig{
    
    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值