首页 > 其他分享 >Spring默认BeanName

Spring默认BeanName

时间:2024-04-02 18:24:30浏览次数:24  
标签:p2024 service Spring BeanName anyway 默认 ALibaba com

先说结论:
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 会输出什么?

标签:p2024,service,Spring,BeanName,anyway,默认,ALibaba,com
From: https://www.cnblogs.com/haicheng92/p/18111243

相关文章