通过Spring注入,获取Service对象实例
2014-01-03 11:43
609 查看
工具类:
package com.lkg.transos.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// TODO Auto-generated method stub
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}
在Spring配置文件(ApplictionContext.xml)中加注入SpringContextUtil对象:
<bean id="SpringContextUtil" class="com.lkg.transos.util.SpringContextUtil"></bean>
获取Service对象实例:
OsAgentExtService osAgentExtService = (OsAgentExtService) SpringContextUtil.getBean("osAgentExtService");
package com.lkg.transos.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// TODO Auto-generated method stub
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}
在Spring配置文件(ApplictionContext.xml)中加注入SpringContextUtil对象:
<bean id="SpringContextUtil" class="com.lkg.transos.util.SpringContextUtil"></bean>
获取Service对象实例:
OsAgentExtService osAgentExtService = (OsAgentExtService) SpringContextUtil.getBean("osAgentExtService");
相关文章推荐
- MyBatis+Spring在注解@Autowried后通过反射的方式调用方法获取注入的Service或DAO对象为空
- 拦截器通过Spring获取工厂类,注入bean对象
- mybatis+spring中的Mapper通过非自动注入方式获取Mapper代理对象(Spring 工厂)
- Spring通过容器获取配置对象及事件注入(学习笔记二)
- spring不通过注入的方式获取对象(BeanFactoryAware \ApplicationContextAware )
- 获取spring注入的service对象
- 如何在自定义标签中获取spring通过@Service注解来的service
- spring 通过中间层工具类SpringBeanFactoryUtils 实现service 注入
- 得到子类反射泛型,以及如何通过注解注入对象(仅供参考,未写实例代码)
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- 通过Class类获取对象(实例讲解)
- Spring在加载后,怎么获取bean且已经是注入好了对象
- spring中通过静态工厂方法获取bean实例化对象
- 在ServletContextListener实现类中获取spring注入对象
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- spring初始化在ServletContextListener实现类中获取spring注入对象
- JSP 获取Spring 注入对象示例
- Spring代码实例系列-01:hellospring(通过xml文件以默认的方式进行setter注入)
- spring 从bean实例中获取对象
- @resource或@Autowired Service service不能通过spring注入问题