请参阅下面的代码:
Point.jave:
package org.dxc.java.technology.part20;
public class Point{
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
Circle.java:
package org.dxc.java.technology.part20;
import javax.annotation.Resource;
public class Circle implements IShape{
private Point center;
public Point getCenter() {
return center;
}
@Resource(name="point1")
public void setCenter(Point center) {
this.center = center;
}
public void draw()
{
System.out.println("X: " + center.getX() + ", Y: " + center.getY());
}
}
spring_part20.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="circle" class="org.dxc.java.technology.part20.Circle">
</bean>
<bean id="point1" class="org.dxc.java.technology.part20.Point">
<property name="x" value="0"></property>
<property name="y" value="0"></property>
</bean>
</beans>
当我得到Circle bean并调用这样的draw方法时:
public class Drive {
static ApplicationContext context = new ClassPathXmlApplicationContext("ConfigurationFiles/spring_part20.xml");
public static void main(String[] args) {
test1();
}
static void test1()
{
IShape shape = (IShape)context.getBean("circle");
shape.draw();
}
}
我收到如下NullPointerException:
Apr 13, 2017 8:44:42 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@497470ed: startup date [Thu Apr 13 08:44:42 CST 2017]; root of context hierarchy
Apr 13, 2017 8:44:42 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ConfigurationFiles/spring_part20.xml]
Exception in thread "main" java.lang.NullPointerException
at org.dxc.java.technology.part20.Circle.draw(Circle.java:19)
at org.dxc.java.technology.part20.Drive.test1(Drive.java:16)
at org.dxc.java.technology.part20.Drive.main(Drive.java:10)
所以,如果我想使用JSR注释来注入bean,是否有人可以告诉我问题是什么以及如何修复它。