《读spring源码》3根据bean注解探索注解形式的bean name是从哪里来的?

我们会发现bean会有一个默认的名字那么这个名字是怎么来的?
在这里插入图片描述

package com.enjoy.cap1;

import com.enjoy.cap1.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {

    public static void main(String args[]){

        ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] beanNamesForType = app.getBeanNamesForType(Person.class);
        for(String beanName:beanNamesForType){
            System.out.println(beanName);
        }
    }
}

package com.enjoy.cap1.config;


import com.enjoy.cap1.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 代表config == 配置文件
 */
@Configuration
public class MainConfig {
    //给容器中配置bean
    @Bean
    public Person person1(){
        return new Person("张三",22);
    }
}

如果把bean的名字改了然后运行程序发现
在这里插入图片描述

bean的名字改变了,而被是配置文件bean的方法名称 也就是在用注解的时候配置bean的时候方法名称对应xml配置文件中的bean id

还有一种方式可以不使用bean的名字为 方法代码如下

package com.enjoy.cap1.config;


import com.enjoy.cap1.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 代表config == 配置文件
 */
@Configuration
public class MainConfig {
    //给容器中配置bean
    @Bean("ssss")
    public Person person1(){
        return new Person("张三",22);
    }
}

测试结果如下:
在这里插入图片描述

我们可以在bean的后面直接指定bean的名称 对应xml中的bean id

发布了434 篇原创文章 · 获赞 58 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/ppwwp/article/details/103301095