gpt4 book ai didi

java - Autowiring 在 Spring 中不起作用

转载 作者:行者123 更新时间:2023-11-29 04:42:50 25 4
gpt4 key购买 nike

我有以下类(class):

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>

问题是 Autowiring 不工作。如果我设置 <property name="A" ref="A"/>等等,不会有 NullPointerException,我可以访问 Point.x 或 Point.y,因此代码编写正确,但如果我按名称 Autowiring , Autowiring 将不起作用,当我尝试从 Triangle 访问 Point.x 时,我得到一个java.lang.NullPointerException .

我试图用 @Autowire 设置类成员 A、B、C , 都带有 @Autowire@Qualifier("A")并且根本没有注释,但它仍然不起作用。

最佳答案

运行程序后的错误:

Bean property 'beanAttribute' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

<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

关于java - Autowiring 在 Spring 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38497131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com