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