Spring中获取bean的三种常用方式
在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);
}
}
总结:在一般情况下,建议使用根据名称+类型来获取Bean,这样能够在获取Bean时更加准确和精确。通过名称+类型来获取Bean可以确保获取到所需要的Bean,避免了可能出现的名称冲突或类型不匹配的情况。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
