转载自:https://my.oschina.net/skyline520/blog/181158?fromerr=GjtR6Wec spring xml中定义 <!--spring 工具类--> <bean id="springContextUtil" class="com.skyline.pub.utils.SpringContextUtil"/> SpringContextUtil的代码如下 package com.skyline.pu…
描述: 在Servlet中调用Spring管理的接口,可以使Dao/Service/ServiceImpl. 前提是在调用的bean中有注解: @Repository("beanName")------------Dao 或者 @Resource("beanName")-----------------Service     代码: private TestDao testDao; //获取ServletContext 再获取 WebApplicationConte…
//从spring容易中获取bean public static Object getBean(String beanName){ ApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); return context.getBean(beanName); } //获取ServletContext public static ServletContext getServletContext(){ W…
1.在项目中添加下面的类: import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. * */ public class SpringContextHolder implem…
WebApplicationContext wac = (WebApplicationContext)config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); dealerArticleService = (DealerArticleService) wac.getBean("dealerArticleService");…
我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用spring提供的其他对象或者说有一些不需要交给spring管理,但是需要用到spring里的一些对象.如果这是spring框架的独立应用程序,我们通过 ApplicationContext ac = new FileSystemXmlApplicationContext("applicationC…
最近由于项目中出现了Servlet调用Spring的bean,由于整个项目中所有的bean均是注解方式完成,如@Service,@Repository,@Resource等,但是Spring的容器管理是不识别Servlet和filter的,所以无法使用注解方式引用,在网上查了资料后看到如下的代码:第一种方式:在Servlet的init方法中来完成bean的实例化,初始化后可以在servlet中调用bean中的方法 WebApplicationContext cont = WebApplicati…
1.再Spring配置文件中配置工具类 <!-- 用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的静态方法得到spring bean对象 --> <bean class="com.xxxxx.SpringContextHolder" lazy-init="false" /> 2.编写java工具类 import org.springframework.context…
package com.yxf.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.…
BeanFactory接口 Interface BeanFactory getBean <T> T getBean(String name, Class<T> requiredType) throws BeansException上面是Apring的bean工厂的接口(顾名思议 拿到Spring的Bean) 下面看它的一个实现类 ClassPathXmlApplicationContext(BeanFactory接口的一个实现类) public ClassPathXmlApplic…