1. 程式人生 > >Spring bean在不同情況下的預設id或name 侵立刪

Spring bean在不同情況下的預設id或name 侵立刪

轉自:https://www.cnblogs.com/1540340840qls/p/6962777.html

 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預設的名字是與方法名相同。

程式碼如下:

123456789101112131415package com.qls.laowei;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/*** Created by ${秦林森} on 2017/6/8.*/@Configurationpublic class OrderConfig {@Beanpublic 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程式碼如下:

1234567891011121314151617package 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的證明思路與上述兩種情況一樣,故不贅述。