我有以下4个班级: CarApplication [主类], 本田延伸车辆, 车辆,和 VehicleType
这是车辆类:
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)
我调试它并发现公共VehicleType类型为null。我做错了吗?
由于
答案 0 :(得分:1)
在下面添加上下文文件:
<context:annotation-config />
需要激活已在应用程序上下文中注册的bean中的注释