春季MVC依赖注入理解



我是Spring MVC的新手

春季示例

在那个示例中,我很清楚依赖注入的概念。但是我有一个小问题,即如何告诉春天我想使用多种形状。在第一个示例(基于构造函数)中,他给了一个圆对象,以便绘制一个圆圈。

<bean id="geometryExample1" class="com.boraji.tutorail.spring.GeometryExample1">
    <constructor-arg ref="circleShape"/>
</bean>

但是,如果要画两个圆,矩形和其他形状,该怎么办?我如何在春季判断或配置,具体取决于我提供的形状,它应该使用适当的形状来绘制形状。

任何帮助将不胜感激。提前致谢。有任何建议吗?

请找到使用Java Config而不是XML配置的教程。如果您学会使用Java Config。

,您的生活将容易得多

自动引导时,您可以指定@Qualifier并通过ID引用BEAN,例如

// This is your circle object
@Autowired
@Qualifier("geometryExample1")
public GeometryExample1 circleShape;

如果有

<bean id="squareExample" class="com.boraji.tutorail.spring.GeometryExample1">
    <constructor-arg ref="squareShape"/>
</bean>

...然后在您的代码中,您将拥有:

// This is your square object
@Autowired
@Qualifier("squareExample")
public GeometryExample1 squareShape;

请参阅春季用注释在春季用名字自动的?有关使用Java Config的bean实例化的示例。

实现您的类:

class CircleShape implements Shape {
    void draw() {
        // TODO implementation
    }
}
class RectangleShape implements Shape {
    void draw() {
        // TODO implementation
    }
}

声明豆:

<bean id="rectangleShape" class="com.boraji.tutorail.spring.RectangleShape" />
<bean id="rectangleShape" class="com.boraji.tutorail.spring.CircleShape" />
<bean id="geometryExample1" class="com.boraji.tutorail.spring.GeometryExample1">
    <constructor-arg ref="rectangleShape"/>
</bean>

Java方法是虚拟的,因此调用了矩形的draw()。更改几何example1 bean构造器arg返回到圆形:

<bean id="geometryExample1" class="com.boraji.tutorail.spring.GeometryExample1">
    <constructor-arg ref="circleShape"/>
</bean>

现在从Circleshape中绘制()称为。

在此处阅读有关虚拟方法的更多信息。请使用注释。

我希望我能正确理解您的问题。

编辑:示例类:

class GeometryExample1 {
    private Set<Shape> shapes;
    void example() {
        shapes.foreach(Shape::draw);
    }
    public void setShapes(Set<Shape> shapes) {
         this.shapes = shapes;
    }
    public Set<Shape> getShapes() {
        return shapes;
    }
 }

和bean声明:

<bean id="geometryExample1" class="com.boraji.tutorail.spring.GeometryExample1">
    <property name="shapes">
        <set>
            <ref bean="circleShape" />
            <ref bean="rectangleShape" />
        </set>
    </property>
</bean>

在这种情况下,注释config应该更清楚。

最新更新