栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ioc容器中的bean的id

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ioc容器中的bean的id

ioc容器中的bean的id的取名方式有4种:

    默认(使用@Autowired时)@Qualifier在xml文件中的bean标签内赋值在java代码配置spring的文件中由@Bean标记的方法名作为id

1、默认
当@Autowired,第一次用类型getBean(Class c)没有找到时,接下来用变量名作为id寻找
eg:

@Autowired
private Student tom;//tom会做为id,当用类型找不到时

2、
如果根据成员变量名作为id还是找不到bean,可以使用
@Qualifier注解明确指定目标bean的id

//@Qualifier注解明确指定目标bean的id
@Qualifier("bookServicehaha")//用bookServicehaha作为id来找组件
    @Autowired
    private BookService bookServiceX2;//此时id名找不到

    public void doGet(){
        System.out.println("BookService..."+bookServiceX2);
    }

3、
    1、在xml文件中显式赋值


id为指定的id名

    2、在xml文件中隐式赋值


id为全限定类名来进行命名。id为com.example.Teacher#0
#0是一种计数的方式,用来区分在容器中其他同类型的bean
0:表示在xml文件中,该类型的声明位置是第一个声明的。

例如:

id为com.examination.util.Book#0

      
  
id为com.examination.util.Book#1
  
      
  

4、在java代码配置spring的文件

//@Bean注解表示将当前方法标记为创建bean的方法
//并且将其创建的bean加入到ioc容器中。
	@Bean
	public Student  myStudent(){
		return new Student();
	}
	

ioc容器中的Student组件的id为 myStudent

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/749272.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号