无法用spring框架运行java,没有命名bean

时间:2017-08-15 14:39:34

标签: java spring netbeans

这是我第一次使用框架,所以我在这里苦苦挣扎,我在网上关注了几个教程,但仍然得到同样的错误.. 这是我的代码

HelloWorld.java

package com.andi.latihanspring;

/**
*
* @author andi
*/
public class HelloWorld {
private String message;

public void getMessage() {
    System.out.println("Your message : "+message);
}

public void setMessage(String message) {
    this.message = message;
}

}

MainApp.java

package com.andi.latihanspring;

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

/**
 *
 * @author andi
 */
 public class MainApp {
    public static void main(String []args){
        ApplicationContext context=new      ClassPathXmlApplicationContext("classpath*:context.xml");
    HelloWorld obj=(HelloWorld)context.getBean("helloWorld");
    obj.getMessage();
}
}

context.xml中

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">


<bean id="helloWorld" class="com.andi.latihanspring.HelloWorld">
    <property name="message" value="Hello Spring!"/>
</bean>

这是输出

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@68de145: startup date [Wed Aug 16 04:34:07 WIB 2017]; root of context hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'helloWorld' is defined
at     org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at com.andi.latihanspring.MainApp.main(MainApp.java:18)

我正在使用netbeans和spring 4.0.1。 我不能继续下一章导致这个错误,非常感谢

0 个答案:

没有答案