Spring Bean 设置不起作用,没有这样的 Bean

Spring Bean setting doesn't work, no such bean

我正在制作一个 Spring Bean 用于练习。 这是非常简单的 bean 设置,但一直显示错误,

NoSuchBeanDefinitionException: No bean named 'bye2' available

这是我的 root-context.xml 文件

<bean id="bye2" class="com.jun.test.Bye2">
    <property name="one" value="one" />
    <property name="two" value="two" />
</bean>

这是 Bean Class,

public class Bye2 {

private String one;
private String two;

public Bye2() {
}

public String getOne() {
    return one;
}

public void setOne(String one) {
    this.one = one;
}

public String getTwo() {
    return two;
}

public void setTwo(String two) {
    this.two = two;
}

这是调用 bean 的主要方法。

public class ByeMain {

    public static void main(String[] args) {
        String Configloc = "classpath:root-context.xml";
        ApplicationContext ctx = new AnnotationConfigApplicationContext(Configloc);
        Bye2 bye2 = ctx.getBean("bye2", Bye2.class);
        bye2.setOne("one");
        bye2.setTwo("Two");
        System.out.println(bye2.getOne());
        System.out.println(bye2.getTwo());
    }

我做错了什么?

AnnotationConfigApplicationContext 的用法不符合您的上下文。您应该使用 ClassPathXmlApplicationContext。在此处查看 AnnotationConfigApplicationContext 的文档:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationConfigApplicationContext.html

所以请尝试以下操作:

AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(Configloc);