2010-11-01 38 views
0

我无法在服务层获取spring bean(ServiceContext.getBean(“beanName”))。我能够在servlet中获得bean。我在下一节课中做错了什么?如何从服务层访问弹簧管理的bean

package com.ekaplus.presentation.common; 

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

public class ServiceContext implements ApplicationContextAware{ 

    private static ApplicationContext applicationContext;  

    @SuppressWarnings("static-access") 
    public void setApplicationContext(ApplicationContext ctx)throws BeansException { 
     this.applicationContext=ctx;   
    } 
    public static ApplicationContext getApplicationContext() { 
     return applicationContext; 
    } 
    public static Object getBean(String beanName) 
    { 
     return applicationContext.getBean(beanName); 
    } 

} 
+0

有没有例外? – 2010-11-01 07:09:58

回答

0

在ear和web-inf lib中有一些libs问题。它正在工作。

0

尝试做到没有静态访问。像这样(仅用于测试)

class ServiceContext { 
    public static Object getBean(final String beanName){ 
     return new ApplicationContextAware(){ 
      Object res; 
      @Override 
      public void setApplicationContext(ApplicationContext applicationContext) 
        throws BeansException { 
       res = applicationContext.getBean(beanName); 
      } 

      Object getBean(){ 
       return res; 
      } 

     }.getBean(); 
    } 
} 
0

是您的Servicecontext由Spring管理。看起来不是。如果它不是由Spring管理的,它不能在您的Servicecontext对象中注入ApplicationContext。

如果你能说出你想要达到的效果,那么它会比较容易建议。特别是ServiceContext的作用是什么?豆不能自动连线?