【问题标题】:@Autowired Annotation in Spring give me NullPointerExceptionSpring 中的 @Autowired 注解给了我 NullPointerException
【发布时间】:2017-08-23 11:00:07
【问题描述】:

我正在尝试在 Spring 中使用 @Autowired 注解进行依赖注入 通过一个简单的程序,但我给了我以下错误

Exception in thread "main" java.lang.NullPointerException
    at Customer.d(Customer.java:8)
    at Main.main(Main.java:12)

通过xml配置它给了我正确的结果。

我的 xml 文件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
  <bean id="person" class="Person">
    <property name="name" value="khan"/>
  </bean>
  <bean id="cust" class="Customer"></bean>
</beans>

客户类别

public class Customer {
@Autowired  
private Person p;
 public void display(){
     System.out.println(p.getName());
 }
}

人物类

public class Person {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;

}

主类

public class Main {
    public static void   main(String[] a) {

        Resource r=new ClassPathResource("SpringXml.xml");
        BeanFactory factory=new XmlBeanFactory(r);
        Customer c=(Customer)factory.getBean("cust");
        c.display();
    }

}

【问题讨论】:

  • 如果上述类不在默认包中,则不要只提及“客户”或“个人”,而是将其更改为 class= “完成包路径.客户”
  • 谢谢以上课程在默认包中
  • 在创建客户对象时尝试使用 ApplicationContext

标签: java spring


【解决方案1】:

这样试试

public static void main(String[] args) throws Exception {
    ApplicationContext context= new ClassPathXmlApplicationContext("SpringXml.xml");
    Customer c = (Customer) context.getBean("cust");
    c.display();
}

【讨论】:

  • BeanFactory和ApplicationContext的区别在documentation中描述
【解决方案2】:

试试这个:

<bean id="person" class="com.yourpackage.Person">
  <property name="name" value="khan"/>
</bean>
<bean id="cust" class="com.yourpackage.Customer">
   <property name="p" ref="person"/>
</bean>

别忘了添加你的完整路径类包

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多