在Spring框架中,一个bean是指由SpringIOC容器管理的一个Java对象。Spring提供了一种依赖注入的机制,可以通过在配置文件中配置bean的定义,实现在代码中通过IOC容器获取bean的实例。
方法一
根据名称获取Bean
public class App {
public static void main(String[] args) {
// 使用容器读出对象
//1.先得到spring上下文对象
//名称要和xml文件相等
ApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
//2.得到Bean[依赖查找][IoC思想的一种实现方式]
//和bean的id必须相同
UserService userService = (UserService) context.getBean("user");
}
}
方法二
根据类型获取Bean
public class GetBeanExample {
public static void main(String[] args) {
//1.先得到容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
//2.使用类型获取Bean
//当同一个类型注入到Spring多个的情况下,使用类型获取Bean就会报错
UserService userService = context.getBean(UserService.class);
}
}
方法三 (推荐)
根据名称+类型来获取Bean
public class GetBeanExample2 {
public static void main(String[] args) {
//1.得到容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("userService");
//2.根据名称+类型来获取Bean
UserService userService = context.getBean("user",UserService.class);
}
}