tags:

views:

50

answers:

2

I am trying to put a "Contract" on a method call. My web application is in Spring 3.

Is writing customs Annotations the right way to go. If so, any pointers( I didn't find anything in spring reference docs).

Should I use tools like "Modern Jass", JML ...? Again any pointers will be useful.

Thanks

A: 

I didn't find an ideal solution to this, interestingly it is a planned feature for the Spring framework (2.0 implemented patch):

http://jira.springframework.org/browse/SPR-2698

The best thing I suggest to use JSR 303 which is for bean validation. AFAIK there are two implementations for this:

There's a guide here for integrating it into Spring, I haven't followed it through but it looks ok:

http://blog.jteam.nl/2009/08/04/bean-validation-integrating-jsr-303-with-spring/

Jon
Is "Validation Rule" same as a Contract? As per your answer, you are using both of them interchangeably. The problem with the validation rule you have suggested above is that it cannot be configured for a method call.
Spring Monkey
Adding bean validation on an field/method/class level is a way of introducing DBC precondition checks into your application. Are you trying to do more than that?
Jon
I am trying to put a contract -- like verify the input of method call is not null, and it has specific value on a method call. I call it contract because this contract should be invoked every time the call to the method happens.I see that in the validation frameworks the validation is not used with AOP, which makes me doubt if we can use validation as a contract.
Spring Monkey
+1  A: 

Using Spring EL and Spring security could get you most of the way. Spring security defines the @PreAuthorize annotation which is fired before method invocation and allows you to use Spring 3's new expression engine, such as:

@PreAuthorize("#customerId > 0")
public Customer getCustomer(int customerId) { .. }

or far more advanced rules like the following which ensures that the passed user does not have role ADMIN.

@PreAuthorize("#user.role != T(com.company.Role).ADMIN)")
public void saveUser(User user) { .. }

You can also provide default values for your contract with the @Value annotation

public Customer getCustomer(@Value("#{434}") int customerId) { .. }

You can even reference system properties in your value expressions.

Setting up Spring security for this purpose is not to hard as you can just create a UserDetailsService that grants some default role to all users. Alternatively you could make you own custom Spring aspect and then let this use the SpelExpressionParser to check method values.

Lars Tackmann