`

Java类如何获取Spring的Bean

阅读更多

 1.创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.

  示例代码:

 


   view plaincopy to clipboardprint?
  import org.springframework.beans.BeansException;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.ApplicationContextAware;
  public class MyApplicationContextUtil implements ApplicationContextAware {
  private static ApplicationContext context;//声明一个静态变量保存
  @Override
  public void setApplicationContext(ApplicationContext contex)
  throws BeansException {
  this.context=contex;
  }
  public static ApplicationContext getContext(){
  return context;
  }

  2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.

  例:

 


   <!-- 这个bean主要是为了得到ApplicationContext 所以它不需要其它属性--> 
  <bean class="org.ing.springutil.MyApplicationContextUtil"></bean>  

  3.有了这个ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象.

 

 

4.在java中获得applicationContext引用:

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

 

public class ApplicationListener implements ServletContextListener {
 private static final Log log = LogFactory.getLog(ApplicationListener.class);

 public void contextDestroyed(ServletContextEvent arg0) {
   
 }

 
 public void contextInitialized(ServletContextEvent evt) {
  System.setProperty("user.timezone", "GMT+0800");// 服务器的时区应该是可以配置的
//  TimeZone.setDefault(TimeZone.getTimeZone("GMT+0800")); //这个真TMD奇怪
  ServletContext sc = evt.getServletContext();

   
  //获取spring上下文
  ServletContext context = evt.getServletContext();
  ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
  System.out.println("在这里向java类中传递ctx参数,可以在这里初始化,启动别的服务");
   
  evt.getServletContext().setAttribute("test",2);
  
   }
 }

 

在web.xml中配置如下:

<listener>
  <listener-class>
   com.listener.ApplicationListener
  </listener-class>
 </listener>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics