Monday, July 22, 2013

18-Introduction-to-Annotations-and-the-Required-Annotation

You can configure properties using annotation also.
@Required – by using this annotation you can skip property configuration from XML, annotation has to set before setter method.
      @Required
      public void setCenter(Point center) {
            this.center = center;
      }
<bean id="circle" class="org.yash.watertechsol.Circle"></bean>

You need to add below annotation class configuration in XML to use annotations in class files.
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"></bean>

spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
           
      <bean id="triangle" class="org.yash.watertechsol.Triangle">
            <property name="pointA" ref="pointA"></property>
            <property name="pointB" ref="pointB"></property>
            <property name="pointC" ref="pointC"></property>
      </bean>

      <bean id="circle" class="org.yash.watertechsol.Circle">
      </bean>
     
      <bean id ="pointA" class="org.yash.watertechsol.Point">
            <property name="x" value="0" />
            <property name="y" value="0" />
      </bean>
     
      <bean id ="pointB" class="org.yash.watertechsol.Point">
            <property name="x" value="-20" />
            <property name="y" value="0" />
      </bean>

      <bean id ="pointC" class="org.yash.watertechsol.Point">
            <property name="x" value="0" />
            <property name="y" value="20" />
      </bean>    
     
      <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"></bean>
</beans>

Circle.java
package org.yash.watertechsol;

import org.springframework.beans.factory.annotation.Required;

public class Circle implements Shape {

      private Point center;

      @Override
      public void draw() {
            System.out.println("Drawing Circle");
            System.out.println("("+center.getX()+", "+center.getY()+")");
      }
     
      public Point getCenter() {
            return center;
      }
     
      @Required
      public void setCenter(Point center) {
            this.center = center;
      }

}

No comments:

Post a Comment