Spring依赖注入示例

时间:2017-12-13 22:24:37

标签: java spring spring-mvc dependency-injection

我正在开发Spring依赖注入。

我想使用spring计算矩形和圆的面积并使用依赖注入。

直到现在我已经完成了这个:

接口

public interface Shape {
   double calculateArea();
}

圈子类

public class Circle implements Shape{

    @Autowired
    public double radius;

    @Override
    public double calculateArea() {
        double area = (Math.PI)*radius*radius;
        return area;
    }

}

矩形类:

public class Rectangle implements Shape {

    @Autowired
    public double length;

    @Autowired
    public double breadth;

    @Override
    public double calculateArea() {
        double area = length*breadth;
        return area;
    }
}

bean xml:

<bean id="circle" class="org.package.test.Circle">
    <property name="radius" value="12"/>
</bean>
<bean id="rectangle" class="org.package.test.Rectangle">
    <property name="length" value="12"/>
    <property name="breadth" value="10"/>
</bean>

<bean id="geometricalShape" class="org.package.test.GeometricalShape">
    <constructor-arg ref="circle"/>
    <constructor-arg ref="rectangle"/>
</bean>

GeometricalShape.java

private Shape shape;

private Shape shape1;
   /**
    * Inject circle object via Constructor
    */
   public GeometricalShape(Shape shape,Shape shape1) {
      this.shape = shape;
      this.shape1 = shape1;
   }

   public void calculate() {
      shape.calculateArea();
      shape1.calculateArea();
   }
}

Main.Java

public class Main {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");

        GeometricalShape bean1=context.getBean("geometricalShape", GeometricalShape.class);
        geometryBean1.calculate();           
    }
}

这里我直接提供半径/长度或宽度作为静态值。我如何将其作为动态值提供(这是我想要的任何值,在Spring中更改它?)有没有更好的方法使用Spring依赖注入?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您正尝试将标量值自动装入CircleRectangle类。这不行。正确的解决方案是使用Spring的 @Value 注释,该注释将由BeanPostProcessor执行并为您注入。

<bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
        </list>
    </property>
    <property name="properties">
        <value>
            circle.radius=12
            rectangle.length=12
            rectangle.breadth=10
        </value>
    </property>
</bean>

然后你可以做的是:

public class Circle implements Shape{

    @Value("#{circle.radius}")
    public double radius;

    @Override
    public double calculateArea() {
        double area = (Math.PI)*radius*radius;
        return area;
    }

}

甚至在你的bean定义中你可以像这样定义它

<bean id="circle" class="org.package.test.Circle">
    <property name="radius" value="#{circle.radius}"/>
</bean>

您可以在我的示例中看到PropertyPlaceholderConfigurer也具有locations属性,因此您可以将此值移动到文件中。 Spring也可以从Environment变量或System属性中读取它。我建议阅读Spring's reference documentation.

相关问题