Spring Boot 获取 Bean 的 3 种方式!还有谁不会?
warning:
这篇文章距离上次修改已过419天,其中的内容可能已经有所变动。
在Spring Boot中,获取Bean的常用方式有以下三种:
- 使用
@Autowired注解自动装配:
@Autowired
private YourBeanClass yourBean;- 使用
ApplicationContext获取:
@Autowired
private ApplicationContext context;
public YourBeanClass getYourBean() {
return context.getBean(YourBeanClass.class);
}- 使用
@Bean注解的方法直接调用:
@Configuration
public class YourConfig {
@Bean
public YourBeanClass yourBean() {
return new YourBeanClass();
}
}
public class YourClass {
@Autowired
private YourConfig yourConfig;
public void someMethod() {
YourBeanClass yourBean = yourConfig.yourBean();
// 使用 yourBean
}
}这三种方式是在Spring框架中获取Bean的常用方法,分别适用于不同的场景。
评论已关闭