org.springframework.beans.factory.CannotLoadBeanClassException

时间:2016-09-03 11:11:08

标签: java spring exception spring-4

我发现了一个简单的问题并寻求帮助。 有异常消息:     在上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.CannotLoadBeanClassException:找不到类路径资源[beans.xml]中定义的名称为'us'的bean的class [factory];嵌套异常是java.lang.ClassNotFoundException:factory

这里是界面:     包net.runze.spr1.factory;

public interface Person {
    public void testBeing();
}

这里是class cn

package net.runze.spr1.factory;

public class CN implements Person {

    @Override
    public void testBeing() {
        System.out.println("china");
    }

}

这是我们的课程:

package net.runze.spr1.factory;

public class US implements Person {

    @Override
    public void testBeing() {
        System.out.println("lalalala US");
    }

}

这是工厂:

package net.runze.spr1.factory;

public class PersonFactory {
    public Person getPerson(String arg) {
        if ("cn".equalsIgnoreCase(arg)) {
             return new CN();
        } else {
             return new US();
        }
    }
}

这是我的xml

<bean id="factory" class="net.runze.spr1.factory.PersonFactory"/>

<bean id="cn" 
        factory-bean="factory" 
        factory-method="getPerson">
    <constructor-arg value="cn"></constructor-arg>
</bean>

<bean id="us" 
        class="factory" 
        factory-method="getPerson">
    <constructor-arg value="us"></constructor-arg>
</bean>

这是我的测试类:

@Test
public void instanceFactorytest1() {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    Person b1 = context.getBean("cn", US.class);
    Person b2 = context.getBean("us", US.class);

    b1.testBeing();
    b2.testBeing();
}

非常感谢

1 个答案:

答案 0 :(得分:0)

现在我知道了。真傻~~ 我在xml文件中错误地认错了

<bean id="us"...> this should be "factory-bean" not class.