0

I have below the interface. I am using Java 7 and Spring 3.0

public interface Maintain{

 void save(Request request);
 Request getRequest(String id);
 void delete(Request request);
 void update(Request request);

}

public class MaintainImpl implements Maintain{


 public void save(Request request){

  //Need to validate the request before saving.
  //Need to throw run time exception if validation fails

 }

 public void getRequest(String id){

  //Need to validate the id before getting the results.
  //Need to throw run time exception if validation fails

 }

  //Similarly i  need to implement other 2 methods


}

To validate the requests: I am planning to write one Interface and 4 impl classes which will have validation logic.

public interface validate{

 boolan validate();
}



public class SaveRequestValidator implements validate{

     public boolean validate(){
     //validation logic
    }

   }





 public class GetRequestValidator implements validate{

     public boolean validate(){
     //validation logic
    }

   }




public class DeleteRequestValidator implements validate{

     public boolean validate(){
     //validation logic
    }

   }



public class UpdateRequestValidator implements validate{

     public boolean validate(){
     //validation logic
    }

   }

Now can i perform validations by injecting all these four validators into MaintainImpl.java ?

Is it good practice? Is there any better design? OR can i keep all validations in one class and provide static methods?

Thanks!

user755806
  • 6,565
  • 27
  • 106
  • 153

2 Answers2

1

Spring 3 supports the JSR303 Bean Validation specification - http://docs.spring.io/spring/docs/3.0.0.RC3/reference/html/ch05s07.html.

This means that you can validate certain aspects of (for example your Request) arguments through annotations on the class.

If you want to implement a custom validation method then you should probably use a javax.validation.ConstraintValidator.

Phil Parker
  • 1,557
  • 12
  • 10
0

Since you are using Spring, you can use Spring AOP or AspectJ to do non cross cutting concerns in your application like these validations which you ask for.
Please refer http://docs.spring.io/spring/docs/2.5.4/reference/aop.html

thiyaga
  • 251
  • 1
  • 7
  • thiyaga, could you please provide me any example? Thanks! – user755806 Dec 13 '13 at 12:10
  • Have a look at this url where use of aspect with pointcut is defined. http://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/ . You can use Around annotation to intercept the calls to MaintainImpl and in that Around annotation use validation logic. – thiyaga Dec 13 '13 at 12:30