ApplicationContext beanfactory org.springframework.beans.factory.NoSuchBeanDefinitionException:

时间:2015-04-29 06:43:06

标签: java spring

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

我的代码就像上面一样。 我以两种方式调用getBean。第一种方式运行perfact,但第二种方式抛出异常,如此

  

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有什么区别?我的代码问题是什么?

1 个答案:

答案 0 :(得分:0)

我在application-context.xml

中添加了UserAccountServiceImpl作为bean
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()=com.vl.test.UserAccountServiceImpl@3834d63f]
UserAccountServiceImpl [toString()=com.vl.test.UserAccountServiceImpl@3834d63f]