SpringBoot获取bean的几种方式

目录

一、BeanFactory与ApplicationContext的区别

二、通过BeanFactory获取

三、通过BeanFactoryAware获取

四、启动获取ApplicationContext

五、通过继承ApplicationObjectSupport

六、通过继承WebApplicationObjectSupport

七、通过WebApplicationContextUtils

八、通过ApplicationContextAware

九、通过ContextLoader

十、通过BeanFactoryPostProcessor

十一、通过工具类获取


一、BeanFactory与ApplicationContext的区别

BeanFactory是Spring框架的基础设施,面向Spring本身。ApplicationContext则面向使用Spring框架的开发者,几乎所有的应用场景都可以直接使用ApplicationContext,而非底层的BeanFactory。

ApplicationContext的初始化和BeanFactory有一个重大的区别:

BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean时才实例目标Bean。这样,我们就不能发现一些存在的Spring的配置问题。如果Bean的某一个属性没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常。

而ApplicationContext则在初始化应用上下文时就实例化所有单实例的Bean,相对应的,ApplicationContext的初始化时间会比BeanFactory长一些。

二、通过BeanFactory获取

通过BeanFactory来获取Bean。

基于xml配置文件:(不推荐使用)

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));

User user = (User) beanFactory.getBean("user");
三、通过BeanFactoryAware获取

获取BeanFactory实例最简单的方式就是实现BeanFactoryAware接口。

BeanFactoryAware接口源码:

public interface BeanFactoryAware extends Aware {
?/**
??* 初始化回调方法,Spring会自动将BeanFactory注入进去,接收之后即可使用BeanFactory
??*/
?void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}

BeanFactoryAware属于org.springframework.beans.factory.Aware根标记接口,使用setter注入来在应用程序上下文启动期间获取对象。Aware接口是回调,监听器和观察者设计模式的混合,它表示Bean有资格通过回调方式被Spring容器通知。

示例如下:

@Component
public class BeanFactoryHelper implements BeanFactoryAware {

?private static BeanFactory beanFactory;

?/**
??* 重
Spring Boot应用程序中,获取Bean有多种方式。通常我们会依赖于Spring的上下文管理自动装配所需的组件,但在某些场景下也需要手动去取得某个特定的Bean实例。 ### 方式一:通过@Autowired注解 这是最常见的方式之一,在需要注入的地方直接使用`@Autowired`注解,并声明你要注入的对象类型即可让Spring自动为你找到并赋值相应的bean。 ```java @Service public class MyService { @Autowired private AnotherBean anotherBean; } ``` ### 方式二:利用构造函数或者Setter方法注入(@Inject/@Autowired) 除了字段级别的注入外,还可以选择将依赖项作为构造参数传入,或者是提供setter方法来设置依赖属性。这种方式有助于提高单元测试时的灵活性以及更清晰地表达出类之间的依赖关系。 #### 构造器注入示例: ```java @RestController public class MyController { private final AnotherBean bean; // 使用构造器注入另一个bean public MyController(AnotherBean bean) { this.bean = bean; } } ``` #### Setter方法注入示例: ```java @Component public class MyClass{ private Helper helper; @Autowired public void setHelper(Helper helper){ this.helper=helper; } } ``` ### 方式三:ApplicationContextAware 接口 如果是在非受管环境中想要访问到spring容器里的beans的话,则可以考虑实现 `org.springframework.context.ApplicationContextAware` 接口。这允许我们在任意地方获得整个application context 并从中检索指定名称Bean。 ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component("myAppCtx") public class ApplicationContextProvider implements ApplicationContextAware { private static ApplicationContext ctx = null; public static ApplicationContext getApplicationContext() { return ctx; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ctx = applicationContext; } } // 获取名为 "anotherBean" 的bean 示例: MyClass.anotherBeanInstance = (AnotherBean) ApplicationContextProvider.getApplicationContext().getBean("anotherBean"); ``` ### 方式四:从配置文件加载静态资源或者其他复杂类型的Beans 对于一些比较特殊的场景比如读取外部properties/json/yaml等格式的数据源生成对应的Bean对象,我们一般会采用工厂模式结合@Configuration + @Bean定义的方式来完成。 ```java @Configuration class AppConfig { @Value("${api.url}") String apiUrl; @Bean(name="httpClientConfiguredWithApiUrl") HttpClient createHttpClient(){ return HttpClient.createDefault(apiUrl); } } ``` 以上就是几种常见的在Spring Boot应用里获取、创建和注册Bean的方法了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值