我有以下课程:
public class Triangle implements Shape {
/*@Autowired
@Qualifier("A")*/
private Point A;
/*@Autowired
@Qualifier("B")*/
private Point B;
/*@Autowired
@Qualifier("C")*/
private Point C;
private static AtomicInteger id = new AtomicInteger();
private int ownId;
private int beanAttribute;
@SuppressWarnings("unused")
private int secondaryId;
private String constructor = "Simple type --";
private static final String NAME = "triangle";
Triangle() {
System.out.println("Triangle created without a secondaryId \n");
secondaryId = -1;
}
Triangle(int secondaryId) {
this.secondaryId = secondaryId;
this.ownId = id.addAndGet(1);
}
Triangle(int secondaryId, String constructor) {
this.secondaryId = secondaryId;
this.ownId = id.addAndGet(1);
this.constructor = constructor;
}
public Point getA() {
return A;
}
public void setA(Point a) {
A = a;
}
public Point getB() {
return B;
}
public void setB(Point b) {
B = b;
}
public Point getC() {
return C;
}
public void setC(Point c) {
C = c;
}
public int getOwnId() {
return ownId;
}
}
使用以下XML配置:
<beans>
<bean id="triangleDouble" class="draw.Triangle"
scope="prototype" autowire="byName">
<constructor-arg index="1" value="Double type ++" />
<constructor-arg index="0" value="0" />
<property name="beanAttribute" value="2" />
</bean>
<bean id="triangleSimple" class="draw.Triangle"
scope="prototype" autowire="byName">
<constructor-arg value="1" />
<property name="beanAttribute" value="1" />
</bean>
<bean id="A" class="draw.Point">
<property name="x" value="1" />
<property name="y" value="2" />
</bean>
<bean id="B" class="draw.Point">
<property name="x" value="2" />
<property name="y" value="3" />
</bean>
<bean id="C" class="draw.Point">
<property name="x" value="3" />
<property name="y" value="4" />
</bean>
</beans>
问题是自动装配不起作用。如果我设置<property name="A" ref="A"/>
等,就没有NullPointerException,我可以访问Point.x或Point.y,所以代码写得正确,但如果我通过名称自动装配,自动装配将无法工作,何时我会尝试从Triangle访问Point.x我得到一个java.lang.NullPointerException
。
我尝试使用@Autowire
设置班级成员A,B,C,@Autowire
和@Qualifier("A")
并且根本没有注释,但它仍然没有工作
答案 0 :(得分:2)
运行程序后的错误:
Bean属性&#39; beanAttribute&#39;不可写或具有无效的setter 方法。 setter的参数类型是否与返回类型匹配 吸气鬼?
<context:annotation-config />
<bean id="triangleDouble" bean id="triangleDouble" class="draw.Triangle"
scope="prototype" autowire="byName">
<constructor-arg index="1" value="Double type ++" />
<constructor-arg index="0" value="0" />
<property name="beanAttribute" value="2" />
</bean>
你错过了beanAttribute的setter方法。添加相同的方法,它应该可以工作。
有关详细信息,请参阅setter-injection
答案 1 :(得分:1)
将Point bean名称重命名为小写,并将“setA()”,“setB”等setter添加到Triangle类中。它将解决问题。
麻烦的是你没有遵循JavaBeans惯例。