2015-04-29 94 views
0
UserAccountServiceImpl service = applicationContext.getBean("UserAccountServiceImpl", UserAccountServiceImpl.class); 
service =SpringContextListener.getBean("UserAccountServiceImpl", UserAccountServiceImpl.class); 

我的代碼就像上面那樣。 我援引的getBean兩個ways.The第一種方式perfact跑,但第二個拋出這樣ApplicationContext beanfactory org.springframework.beans.factory.NoSuchBeanDefinitionException:

org.springframework.beans.factory.NoSuchBeanDefinitionException異常:無豆命名爲「UserAccountServiceImpl」被定義

applictionContext從implements ApplicationContextAware SpringContextListener得到的是象下面這樣:

<bean id="springContextListener" class="com.xxxx.xxx.SpringContextListener"/> 

public final class SpringContextListener implements BeanFactoryAware { 

    private static BeanFactory beanFactory; 

    public static BeanFactory getBeanFactory() { 
     return beanFactory; 
    } 

    public void setBeanFactory(BeanFactory beanFactory) { 
     if(SpringContextListener.beanFactory != null) { 
      throw new RuntimeException("beanFactory inited ............."); 
     } 
     SpringContextListener.beanFactory = beanFactory; 
    } 

    public static <T> T getBean(String beanName, Class<T> clazs) { 
     return clazs.cast(beanFactory.getBean(beanName)); 
    } 
} 

applicationContext和beanfactory有什麼區別?我的代碼的問題是什麼?

+0

您的代碼是不完整的。你不會在任何地方調用'SpringContextListener.setBeanFactory'。沒有這個,這個問題就沒有意義了。 – skaffman

+0

您是否在應用程序上下文中定義了UserAccountServiceImpl bean?或者它應該是'UserAccountService'? –

回答

0

我已經在應用程序的context.xml添加UserAccountServiceImpl

ApplicationContext applicationContext = 
    newClassPathXmlApplicationContext("application-context.xml"); 

UserAccountServiceImpl service = applicationContext.getBean("UserAccountServiceImpl", 
    UserAccountServiceImpl.class); 

System.out.println(service); 

service=SpringContextListener.getBean("UserAccountServiceImpl",UserAccountServImpl.class); 

System.out.println(service); 

結果:

UserAccountServiceImpl [toString()[email protected]] 
UserAccountServiceImpl [toString()[email protected]] 
+0

添加到application-context.xml中,如下所示:

+0

謝謝!你的回答是解決我的問題的正確方法。但不是確切的結果最後,我知道原因。這個標籤應該在\t之前添加UserAccountServiceImpl獲取beanfactory! –

相關問題