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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM