Spring Boot获取Bean的三种方式
warning:
这篇文章距离上次修改已过436天,其中的内容可能已经有所变动。
在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
YourConfig yourConfig;
public void someMethod() {
YourBeanClass yourBean = yourConfig.yourBean();
// 使用 yourBean
}
}以上三种方式是在Spring框架中获取Bean的常见方式,分别适用于不同的场景。
评论已关闭