ApplicationContextAware动态获取spring bean

本文介绍如何在代码中动态获取Spring容器内的其他bean,包括实现步骤、配置细节及关键方法使用,助您轻松掌握Spring框架的动态注入机制。

场景:

在代码中需要动态获取其它bean

实例代码:

package org.company.xxx;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取spring容器,以访问容器中定义的其他bean
 */
public class SpringContextUtil implements ApplicationContextAware {

	// Spring应用上下文环境
	private static ApplicationContext applicationContext;

	/**
	 * 实现ApplicationContextAware接口的回调方法,设置上下文环境
	 */
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取对象 这里重写了bean方法,起主要作用
	 * 
	 * @param name
	 * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>  Object 一个以所给名字注册的bean的实例
	 * @throws BeansException
	 */
	public static Object getBean(String beanId) throws BeansException {
		return applicationContext.getBean(beanId);
	}
}

Bean配置:

1 <beanid="SpringContextUtil"class="org.company.xxx.SpringContextUtil"/>

注:

1、实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!

2、通过调用静态方法getBean即可获取


### 实现基于 ApplicationContextAwareSpring Bean 工具类 在 Spring 框架中,`ApplicationContextAware` 接口提供了一种机制,使得某个类能够访问到当前的 `ApplicationContext`。通过实现该接口,可以创建一个工具类,用于全局获取 Spring 容器管理的 Bean 实例。 #### 核心步骤 1. 创建一个工具类并实现 `ApplicationContextAware` 接口。 2. 重写 `setApplicationContext` 方法,将传入的 `ApplicationContext` 存储为静态变量,以便后续使用。 3. 提供一些静态方法,例如根据 Bean 名称、类型或注解获取 Bean 实例。 4. 使用 `@Component` 注解将工具类注册为 Spring 管理的 Bean。 #### 示例代码 下面是一个完整的示例,展示如何实现一个 Spring Bean 工具类: ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import java.util.Map; @Component public class SpringBeanUtils implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } /** * 根据 Bean 名称获取对应的实例 */ public static Object getBean(String beanName) { return context.getBean(beanName); } /** * 根据 Bean 类型获取对应的实例 */ public static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } /** * 根据 Bean 名称和类型获取对应的实例 */ public static <T> T getBean(String beanName, Class<T> beanClass) { return context.getBean(beanName, beanClass); } /** * 获取带有特定注解的所有 Bean */ public static <A extends java.lang.annotation.Annotation> Map<String, Object> getBeansWithAnnotation(Class<A> annotationType) { return context.getBeansWithAnnotation(annotationType); } /** * 获取配置文件中的属性值 */ public static String getProperty(String key) { return context.getEnvironment().getProperty(key); } } ``` #### 使用说明 1. **注入工具类**:由于 `SpringBeanUtils` 被标记为 `@Component`,Spring 会自动将其注册为容器中的 Bean,并调用 `setApplicationContext` 方法初始化上下文。 2. **获取 Bean 实例**: - 可以通过名称获取 Bean: ```java MyService myService = (MyService) SpringBeanUtils.getBean("myService"); ``` - 或者通过类型获取 Bean: ```java MyService myService = SpringBeanUtils.getBean(MyService.class); ``` - 如果存在多个相同类型的 Bean,可以通过名称和类型结合的方式获取: ```java MyService myService = SpringBeanUtils.getBean("myService", MyService.class); ``` 3. **获取带注解的 Bean**: - 假设有一个自定义注解 `@MyCustomAnnotation`,可以通过以下方式获取所有带有该注解的 Bean: ```java Map<String, Object> beans = SpringBeanUtils.getBeansWithAnnotation(MyCustomAnnotation.class); for (Map.Entry<String, Object> entry : beans.entrySet()) { System.out.println("Bean Name: " + entry.getKey() + ", Bean Instance: " + entry.getValue()); } ``` 4. **获取配置属性**: - 可以从 `application.properties` 或 `application.yml` 中读取配置项: ```java String dbUrl = SpringBeanUtils.getProperty("spring.datasource.url"); ``` #### 注意事项 - 确保工具类被正确注册为 Spring Bean,否则 `setApplicationContext` 方法不会被调用。 - 在非 Spring 管理的类中使用该工具类时,需确保 Spring 上下文已经加载完成。 - 避免在工具类中直接依赖其他 Bean,除非这些 Bean 也由 Spring 管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值