注册组件
介绍如下几种给容器中注册组件的方法。
@Configuration+@Bean
@Configuration
public class BeanConfig {
@Bean("student2")
public Student student(){
return new Student("李四",29);
}
}
使用@Bean注解给容器中注入组件时,如果不在@Bean属性中指定名字,那么@Bean所标注的方法名就是该组件在容器中的名字。
测试代码如下:
@Test
public void testBean(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
Student student2 = applicationContext.getBean("student2", Student.class);
System.out.println(student2);
}