上下文是刷新的,但无法获取声明的bean的实例

时间:2018-01-14 11:30:09

标签: java spring

尝试运行简单的spring代码,获取NoSuchBeanDefinitionException。 在beans.xml中定义了一个id为“ - sayHelloImpl”的类。 创建了ClassPathXmlApplicationContext类的applicationContext,并提供了beans.xml文件的路径。调用.getBean(“sayHelloImpl”)获取NoSuchBeanDefinitionException。

  

的beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context  
  http://www.springframework.org/schema/context/spring-context-4.1.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

<bean id="sayHelloImpl" class = "com.Impl.SayHelloImpl"></bean>

</beans>
  

SayHelloImpl.java文件

package com.Impl;
import org.springframework.stereotype.Service;
import com.Interface.SayHello;

@Service("sayHelloImpl")
public class SayHelloImpl implements SayHello {
    @Override
    public String helloSpring() {
        System.out.println("inside helloSpring()");
        return "Hello Spring 4.1.7";
    }
}
  

Main.java文件

package com.Main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.Interface.SayHello;

public class Main {
    public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "classpath*:beans.xml");

    SayHello hello = (SayHelloImpl) applicationContext
            .getBean("sayHelloImpl");

    System.out.println(hello.helloSpring());
    }
}

执行这个主文件后,我在控制台上遇到异常,

Jan 14, 2018 4:51:15 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d099f62: startup date [Sun Jan 14 16:51:15 IST 2018]; root of context hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sayHelloImpl' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at com.Main.Main.main(Main.java:14)

0 个答案:

没有答案