【问题标题】:Spring Inheritance not workingSpring继承不起作用
【发布时间】:2016-03-24 16:07:48
【问题描述】:

我有以下 4 个课程: CarApplication [主类], 本田扩展车辆, 车辆和 车辆类型

这是车辆类别:

import org.springframework.beans.factory.annotation.Autowired;
public class Vehicle {

    @Autowired
    public VehicleType type;
    public String getType() {
        return type.getType();
    }
}

这是本田级:

public class Honda extends Vehicle{

    private String motor = "honda motor";

    public void displayMotor(){
        System.out.println(motor);


        System.out.println(getType()); 
    }

}

这是 VehicleType 类:

public class VehicleType {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }


}

这是主类:

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

public class CarApplication {

    public static void main(String[] args) {


        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        Honda honda = (Honda)ctx.getBean("honda");
        honda.displayMotor();



    }

}

以下是我的 Spring 上下文文件:

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <bean id="honda" class = "mq.spring.practice1.Honda" parent ="vehicle"/>
    <bean id="vehicle" class = "mq.spring.practice1.Vehicle"/>
    <bean id ="type" class="mq.spring.practice1.VehicleType">
        <property name="type" value="car"/>
    </bean>






 </beans>

运行时出现以下错误:

Exception in thread "main" honda motor java.lang.NullPointerException
  at mq.spring.practice1.Vehicle.getType(Vehicle.java:11)
  at mq.spring.practice1.Honda.displayMotor(Honda.java:11)
  at mq.spring.practice1.CarApplication.main(CarApplication.java:15)

我调试它,发现 public VehicleType 类型为空。我是不是做错了什么?

谢谢

【问题讨论】:

  • 我不是 Spring 注释专家,但是如果您没有 setType(VehicleType type) 方法,将如何在 Vehicle 中注入类型。
  • 如果使用注解 (@Autowired),则不需要 Setter 方法。如您在上下文 .xml 中所述,Spring 容器将自动创建该对象的实例。如果你不使用注解,那么你必须使用 setter 和 getter 方法来调用注入。请记住,该类的变量名必须与 bean id 相同。
  • 你是对的。我来自旧版本的 Spring。必须多学习,对不起。

标签: java spring


【解决方案1】:

在上下文文件中添加以下内容:

<context:annotation-config />

需要激活已在应用程序上下文中注册的 bean 中的注释

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2015-03-04
    • 2012-06-04
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2011-03-09
    • 2016-08-28
    相关资源
    最近更新 更多