在普通Java类里使用spring配置文件里的bean类如dao,service
2017-10-18 11:43
751 查看
原文地址:http://blog.csdn.net/tianyaleixiaowu在spring管理的web项目里,譬如Struts和spring的项目,配置好后,Struts里就可以直接使用定义好的service。但是如果要在普通的工具类里,使用service或dao,就会报空指针,因为这个普通的Java类并不在spring管理下,不能使用spring注入的service。下面讲一个方法,让普通工具类也能使用service。定义一个类 SpringTool
<bean class="app.util.spring.SpringTool"/>
然后就可以了,就可以在任何一个普通的工具类里,根据spring里配置好的bean的id,得到这个注入好的对象
/** * 通过该类即可在普通工具类里获取spring管理的bean * @author wolf * */ public final class SpringTool implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringTool.applicationContext == null) { SpringTool.applicationContext = applicationContext; System.out.println( "========ApplicationContext配置成功,在普通类可以通过调用ToolSpring.getAppContext()获取applicationContext对象,applicationContext=" + applicationContext + "========"); } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } }然后将这个类,加入到spring的配置文件里,
<bean class="app.util.spring.SpringTool"/>
然后就可以了,就可以在任何一个普通的工具类里,根据spring里配置好的bean的id,得到这个注入好的对象
import app.util.spring.SpringTool; public class Test { public void print() { ArticleService articleService = (ArticleService) SpringTool.getBean("articleService"); Article article = articleService.queryById(756); System.out.println(article.getTitle()); } }
相关文章推荐
- 在普通Java类里使用spring里注入的service、dao等
- 在普通Java类里使用spring里注入的service、dao等
- Java opencsv--使用 Spring 的 PostConstruct机制,项目启动时,将CSV配置文件读取到内存 map 中
- Spring配置文件加载时出现Bean property 'newscontentDAO' is not writable or has an invalid setter method错误的解决
- java spring配置文件applicationcontext.xml的使用
- Spring-Bean配置-使用外部属性文件
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- Java 学习笔记04:Spring XML配置文件Bean
- SPRING IN ACTION 第4版笔记-第二章WIRING BEANS-008-在XML配置文件中引入JAVA配置文件 <import> 、<bean>
- java代码中获得spring配置文件中的bean
- web工程中普通 java 类使用 properties 配置文件中属性
- 使用dom4j:读取spring配置文件,实例化bean对象并注入依赖对象
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得ApplicationContext的方法
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- 使用反射创建Bean、Spring中是如何根据类名配置创建Bean实例、Java提供了Class类获取类别的字段和方法,包括构造方法
- Spring配置文件中使用ref local与ref bean的区别. 在ApplicationResources.properties文件中,使用<ref bean>与<ref local>方法如下
- [java][spring]取得通过配置文件和注解注入的bean、取得当前数据库连接、取得Appli
- Spring配置文件中使用ref local与ref bean的区别