我正在练习Spring基础知识,并且了解如果未指定for bean,则@Required自动将bean byName绑定。
但是,它对我不起作用。 PFB的一组类和配置文件-
主类:
public class DrawingApp {
public static void main(String[] args) {
AbstractApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
Shape shape = (Shape)ac.getBean("shape");
shape.draw();
ac.registerShutdownHook();
}
}
Circle.java:
public class Circle implements Shape {
Point centre;
@Override
public void draw() {
System.out.println("Drawing Circle");
System.out.println("Circle centre is (" + centre.getX() + ", " + centre.getY() + ")");
}
public Point getCentre() {
return centre;
}
@Required
public void setCentre(Point centre) {
this.centre = centre;
}
}
还有spring.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<!-- <context:component-scan base-package="/src/*"/> -->
<bean id='triangle' class='org.mayur.spring.Triangle' autowire="byName">
<property name="type" value="Scalene" />
<property name="height" value="20" />
<property name="width" value="10" />
</bean>
<bean id='pointA' class='org.mayur.spring.Point' name="pointD,pointE pointF">
<property name="x" value="0" />
<property name="y" value="0" />
</bean>
<bean id='pointB' class='org.mayur.spring.Point'>
<property name="x" value="-20" />
<property name="y" value="0" />
</bean>
<bean id='pointC' class='org.mayur.spring.Point'>
<property name="x" value="0" />
<property name="y" value="20" />
</bean>
<bean id='centre' class='org.mayur.spring.Point'>
<property name="x" value="-10" />
<property name="y" value="10" />
</bean>
<bean id='shape' class='org.mayur.spring.Circle'>
</bean>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"></bean>
</beans>
理想情况下,此设置应将“中心” bean注入“ shape” bean中,并应打印圆形draw()方法。
但是,我遇到了异常-
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shape' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'centre' is required for bean 'shape'
请帮助我解决这里的问题?