【SpringBoot_ANNOTATIONS】组件注册 01 @Configuration @Bean

Spring重要特性:IOC/DI (控制反转 / 依赖注入)

传统方式

使用beans.xml

  1. 创建bean类
package com.example.annotations.bean;

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  1. idea中创建beans.xml
    new – xml configuration file – Spring config
    在这里插入图片描述
<bean id="person" class="com.example.annotations.bean.Person">
    <property name="name" value="lxl"/>
    <property name="age" value="21"/>
</bean>
  1. 测试
    @Test
    void beanTest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
    }

注解方式 @Configuration @Bean

  1. 编写MainConfig类:配置类等同于beans.xml

    package com.example.annotations.config;
    
    import com.example.annotations.bean.Person;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    // @Configuration : 告诉Spring这是个配置类
    @Configuration
    public class MainConfig {
    
        //给容器注入一个bean,类型为返回值的类型,id默认使用方法的id
        @Bean("person")
        public Person getPerson(){
            return new Person("qd",21);
        }
    }
    
  2. 测试

        @Test
        void beanConfigTest(){
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
            Person person = applicationContext.getBean(Person.class);
    
            //获取对应类型组件在IOC容器中的名字 返回一个数组
            String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
    //        System.out.println(Arrays.toString(beanNamesForType));
    
            for (String str:beanNamesForType){
                System.out.println("toString:" + str.toString());
            }
        }
    
  3. Notes

    • @Configuration:告诉Spring这是个配置类
    • @Bean:给容器注入一个bean
      • 标注在类上:类型为bean类的类型,id默认为类的小写
      • 标注在方法上:类型为返回值的类型,id默认使用方法的id
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值