我正在制作一个 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 类,
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
的文档:
所以请尝试以下操作:
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(Configloc);
关于java - Spring Bean 设置不起作用,没有这样的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435116/