
Spring提供了多种获取Bean实例的方式,下面就来详解spring获取bean的几种方式@mikechen
1.通过XML配置文件获取
在Spring的XML配置文件中配置Bean定义,然后使用ApplicationContext容器的getBean方法获取Bean实例。
示例:
<bean id="myBean" class="com.example.MyBean"/>
可以使用ApplicationContext容器的getBean方法获取Bean实例:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyBean myBean = (MyBean) context.getBean("myBean");
2.通过Java配置类获取
使用@Configuration和@Bean注解配置Bean定义,然后通过ApplicationContext容器获取Bean实例。
假设有以下Java配置类:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
可以使用ApplicationContext容器获取Bean实例:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MyBean myBean = (MyBean) context.getBean(MyBean.class);
这两种方式都比较简洁、方便,而且在Spring Boot等现代Web应用中已经成为了主流方式。
3.通过注解获取
首先使用注解,比如:@Component、@Service、@Controller、@Repository等标注Bean类。
然后在ApplicationContext容器中自动扫描,然后使用getBean方法获取Bean实例。
假设有以下使用@Component注解的Bean类:
@Component
public class MyBean {
// ...
}
可以使用ApplicationContext容器的getBean方法获取Bean实例:
ApplicationContext context = new AnnotationConfigApplicationContext("com.example");
MyBean myBean = (MyBean) context.getBean(MyBean.class);
4.通过Autowired注解获取Bean实例
假设有以下使用@Autowired注解的类:
@Component
public class MyService {
@Autowired
private MyBean myBean;
// ...
}
可以使用ApplicationContext容器获取Bean实例,并自动注入到MyService类中:
ApplicationContext context = new AnnotationConfigApplicationContext("com.example");
MyService myService = context.getBean(MyService.class);
以上就是spring获取bean的几种方式详解,更多内容请查看:Spring教程(史上最全图文详解)
mikechen睿哥
10年+一线大厂架构实战经验,就职于阿里、淘宝等一线大厂,操盘多个亿级大厂核心项目。