• spring in action 学习笔记六:bean在不同情况下的默认id号或者将名字


      bean如果不知名id是什么它一般都有一个id或者讲名字。

    第一种情况:组件扫描的情况:默认的id号或者bean的name是类名的首字母小写。

    代码如下:

     1 package com.qls.beanlife2;
     2 
     3 import org.springframework.beans.factory.BeanNameAware;
     4 import org.springframework.stereotype.Component;
     5 
     6 /**
     7  * Created by ${秦林森} on 2017/6/7.
     8  */
     9 @Component
      //BeanNameAware这个接口可以获取bean的名字。
    10 public class Teacher implements BeanNameAware { 11 @Override 12 public void setBeanName(String name){ 13 System.out.println("the Teacher bean name is : "+name); 14 } 15 }

    第二种情况:是基于javaConfig显示配置bean时:这个时候bean默认的名字是与方法名相同。

    代码如下:

    package com.qls.laowei;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * Created by ${秦林森} on 2017/6/8.
     */
    @Configuration
    public class OrderConfig {
        @Bean
        public Rice getRice(){
            return  new Rice();
        }
    }
    

    Rice类的代码如下:

     1 package com.qls.laowei;
     2 
     3 import org.springframework.beans.factory.BeanNameAware;
     4 import org.springframework.stereotype.Component;
     5 
     6 import java.util.List;
     7 import java.util.Map;
     8 import java.util.Set;
     9 
    10 /**
    11  * Created by ${秦林森} on 2017/6/7.
    12  */
    13 public class Rice implements BeanNameAware{
    14    
    15     @Override
    16     public void setBeanName(String name) {
    17         System.out.println("the rice's bean name is : "+name);
    18     }
    19    
    20 }

    检验bean的名字为方法名getRice代码如下:

    package com.qls.test;
    
    import com.qls.laowei.OrderConfig;
    import com.qls.laowei.Rice;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * Created by ${秦林森} on 2017/6/8.
     */
    public class Test5 {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(OrderConfig.class);
            Rice rice = ac.getBean(Rice.class);
        }
    }/**output:
     the rice's bean name is : getRice
     */
    

    从上面的输出结果可以看到bean在javaConfig的显性配置下即用@Bean的注解的情况下bean的名字为其方法名。

      第三种情况:

    在配置文件xml中的配置:<bean class="com.qls.Hello"/>

    这个bean的id号默认是com.qls.Hello#0即(包名.类名#自然数)

    这个默认id的证明思路与上述两种情况一样,故不赘述。

  • 相关阅读:
    链式二叉树遍历具体程序
    非线性结构
    函数调用
    递归
    队列的操作
    MFC多线程详细讲解(转)
    PreTranslateMessage()函数捕获键盘按键消息
    vc和halcon数据的相互赋值
    VC6.0加载lib文件的三种方法
    MFC中按钮控件的用法笔记(转)
  • 原文地址:https://www.cnblogs.com/1540340840qls/p/6962777.html
Copyright © 2020-2023  润新知