Announcement Announcement Module
Collapse
No announcement yet.
Bean Validation Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Bean Validation

    Hi All,

    I am new to Spring Framework. I was trying to do a Simple Validation on one of my bean. Since i don't want to use the MVC frmamework can somebody help me out in doing that.

    Here is my code.

    package example;

    import org.springframework.context.ResourceLoaderAware;
    import org.springframework.core.io.ResourceLoader;


    public class Person implements ResourceLoaderAware {

    private String name;
    private int age;

    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public void setResourceLoader(ResourceLoader arg0) {
    }

    }


    package example;

    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.validation.Validator;

    public class PersonValidator implements Validator {

    public boolean supports(Class clzz) {
    return Person.class.equals(clzz);
    }

    public void validate(Object obj, Errors e) {
    ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
    Person p = (Person)obj;
    if (p.getAge() < 0) {
    e.rejectValue("age", "negativevalue");
    } else if (p.getAge() > 110) {
    e.rejectValue("age", "tooold");
    }
    }

    }


    <bean id="person" class="example.Person">
    <property name="name">
    <value> Amit Kaushik </value>
    </property>
    <property name="age">
    <value> -28 </value>
    </property>
    <property name="validator">
    <bean class="example.PersonValidator"/>
    </property>

    </bean>


    I want to use PersonValidator Class to validate Person's class properties. Do i need to call explicitly the PeronValidator method in to Perosn's setResourceLoader method or is there any other way of doing this.

    Any help will be appreciated.

    Thanks,
    Amit
Working...
X