Spring默認BeanName

先說結論:
1、XML配置和註解生成默認BeanName的機制是不同的
2、XML配置默認BeanName = 全類名 + # + 數字,如 com.anyway.p2024.service.impl.BigHouseServiceImpl#0
3、註解默認BeanName = 短類名首字母變成小寫,如 bigHouseServiceImpl
注意:如果短類名前2個字母都是大寫,則保持短類名不變,比如 ALibaba

示例

com.anyway.p2024.service.BigHouseService

public interface BigHouseService {  
}

com.anyway.p2024.service.impl.BigHouseServiceImpl

@Service  
public class BigHouseServiceImpl implements BigHouseService {  
}

com.anyway.p2024.service.impl.BigHouseServiceImpl2

@Service  
public class BigHouseServiceImpl2 implements BigHouseService {  
}

com.anyway.p2024.domain.ALibaba

@Component  
public class ALibaba {  
}

applicationContext.xml

<context:annotation-config />  
<context:component-scan base-package="com.anyway" />  
  
<bean class="com.anyway.p2024.service.impl.BigHouseServiceImpl" />  
<bean class="com.anyway.p2024.domain.ALibaba" />  
<bean class="com.anyway.p2024.domain.ALibaba" />

Demo04.java

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");  
System.out.println(JSON.toJSON(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ac, BigHouseService.class)));  
System.out.println(JSON.toJSON(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ac, ALibaba.class)));

輸出如下:

["bigHouseServiceImpl","bigHouseServiceImpl2","com.anyway.p2024.service.impl.BigHouseServiceImpl#0"]
["ALibaba","com.anyway.p2024.domain.ALibaba#0","com.anyway.p2024.domain.ALibaba#1"]

思考題:
如果將 com.anyway.p2024.domain.ALibaba 複製到 com.anyway.p2024.service.ALibaba ,執行 Demo04.java 會輸出什麼?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章