0
点赞
收藏
分享

微信扫一扫

ioc容器中的bean的id

三维控件研究 2022-03-10 阅读 56

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

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

1、默认
当@Autowired,第一次用类型getBean(Class<T> 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、在xml文件中显式赋值

<bean class="com.example.Teacher" id="myTeacher"/>

如果不指定id,只能用getBean(Class<T> c)来获取组件

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

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

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

举报

相关推荐

0 条评论