获取Spring管理的Bean方法

在Java Application运行中常常需要获取当前JVM里存在的Spring Bean资源,本帖即提供方法在Java中获取Spring管理的Bean

示例项目基于SpringMVC,可以参考我的博文创建Spring MVC项目在STS IDE


有以下三种方法获得Spring管理的Bean:(推荐方案三)

方案一

当使用Spring的DispatcherServlet方式加载时

所需配置:

【web.xml】配置

<!-- Processes application requests -->
<servlet>  
	<servlet-name>appServlet</servlet-name>  
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
	<init-param>  
		<param-name>contextConfigLocation</param-name>  
		<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>  
</servlet>

获取Spring管理的Bean实现:

Java代码

	ServletContext sc = getServletContext();  
	WebApplicationContext attr = (WebApplicationContext)sc.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");  
	sc.getBean("[Bean Name]");

ServletContext的key是org.springframework.web.servlet.FrameworkServlet.CONTEXT.appServlet,

注意后面的appServlet,是servlet-name配置的值,需要根据web.xml的配置适时修改。



方案二:

当使用Spring的ContextLoaderListener方式加载时

所需配置:

【web.xml】配置

<context-param>  
	<param-name>contextConfigLocation</param-name>  
	<param-value>/WEB-INF/spring/root-context.xml</param-value>  
</context-param>  
  
<listener>  
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener> 

获取Spring管理的Bean实现:

Java代码

	ServletContext sc = getServletContext();  
	WebApplicationContext applicationContext  = WebApplicationContextUtils .getWebApplicationContext(sc);   
	applicationContext.getBean("[Bean Name]");



方案三(推荐):

通用的方法,将以静态变量保存Spring ApplicationContext,通过Spring在加载时注入,可以在任何需要时提取ApplicationContext使用以获取Bean。

所需配置:

【web.xml】配置

<context-param>
	<param-name>contextConfigLocation</param-name>  
	<param-value>/WEB-INF/spring/root-context.xml</param-value>  
</context-param>


【root-context.xml】配置

	<bean class="com.tanksoft.spring.general.SpringContextHolder" lazy-init="false" />


【com.tanksoft.spring.general.SpringContextHolder.java】实现类

package com.tanksoft.spring.general;

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

/**
 * @author tanksoft
 *
 */
public class SpringContextHolder implements ApplicationContextAware {
	
	/**
	 * Static Spring ApplicationContext for get spring beans 
	 */ 
	private static ApplicationContext applicationContext;  

	/** 
	 * Initialize ApplicationContext
	 */
	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
	}
	
	/** 
	 * Get ApplicationContext
	 */  
	public static ApplicationContext getApplicationContext() {  
		checkApplicationContext();  
		return applicationContext;  
	}
	  
	/** 
	 * Get Bean from ApplicationContext with bean name
	 */  
	public static Object getBean(String name) {  
		checkApplicationContext();  
		return applicationContext.getBean(name);  
	}  
	  
	/** 
	 * clean applicationContext 
	 */  
	public static void cleanApplicationContext() {  
		applicationContext = null;  
	}  
	  
	private static void checkApplicationContext() {  
	if (applicationContext == null) {  
		throw new IllegalStateException("applicaitonContext do not exist, please check root-context.xml SpringContextHolder");  
	}  
	}

}

获取Spring管理的Bean实现:

Java代码
	import com.tanksoft.spring.general.SpringContextHolder;   
	......
	SpringContextHolder.getBean("[Bean Name]");

完成!

Spring获取某个注入bean的指定方法,可先获取bean的实例,再调用其指定方法。 ### 方法一:通过`ContextLoader`获取`WebApplicationContext` 若在Web应用里,可借助`ContextLoader`获取`WebApplicationContext`,再通过它得到bean实例,进而调用指定方法。示例代码如下: ```java import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; // 获取WebApplicationContext WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); // 获取指定ID的bean实例 Object bean = wac.getBean(beanID); // 假设bean是ValueGenerator类型,调用其getAgeValue方法 if (bean instanceof com.b510.app.util.ValueGenerator) { com.b510.app.util.ValueGenerator valueGenerator = (com.b510.app.util.ValueGenerator) bean; int age = valueGenerator.getAgeValue(); } ``` 此方法适用于Web应用环境,能在代码里获取Spring上下文并获取指定bean实例,调用其方法 [^3]。 ### 方法二:注入Bean并调用方法 可在类中直接注入需要的bean,之后调用其方法。示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyService { @Autowired private com.b510.app.util.ValueGenerator valueGenerator; public void doSomething() { // 调用注入bean的指定方法 int age = valueGenerator.getAgeValue(); } } ``` 这种方法需在Spring管理的组件里使用`@Autowired`注解注入bean,随后调用其指定方法。 ### 方法三:使用`MethodInvokingFactoryBean`注入方法返回值 若想注入某个bean方法返回值,可使用`MethodInvokingFactoryBean`。示例如下: ```xml <bean id="valueGenerator" class="com.b510.app.util.ValueGenerator" /> <bean id="ageValue" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="valueGenerator" /> <property name="targetMethod" value="getAgeValue" /> </bean> ``` 上述配置里,通过`MethodInvokingFactoryBean`注入`valueGenerator` bean的`getAgeValue`方法的返回值 [^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值