2016-03-24 149 views
0

我有以下4类: CarApplication [主类], 本田延伸车辆, 车辆,和 VehicleType弹簧继承不工作

这是车辆类别:

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

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

这是本田Class:

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) 

我调试它,发现公共VehicleType类型是 空值。难道我做错了什么?

感谢

+0

我不是Spring注解专家已注册的bean的注解,但怎么会是如果您没有setType(VehicleType类型)方法,则在Vehicle中注入类型。 – RubioRic

+1

如果使用注释(@Autowired),则不需要Setter方法。正如您在上下文.xml中所述,Spring容器将自动创建该对象的一个​​实例。如果你不使用注释,那么你必须使用setter和getter方法来调用注入。请记住,该类的变量名必须与bean id相同。 – user1459497

+0

你说得对。我来自Spring的旧版本。必须多学习,对不起。 – RubioRic

回答

1

下面添加到关联文件:

<context:annotation-config /> 

需要激活的应用程序上下文

+0

它工作。谢谢 – user1459497