Donnerstag, 27. Oktober 2011

Spring DI with Java Standard Annotations

In Spring it is easy to use the Java annotations for dependency injection (JSR 330), the Java annotation for post construct and pre destroy (JSR 250) and the Java API and Annotations for validation (JSR 303).

Why should I use this standard APIs and annotation in a Spring based application? Because when using this standards, the code has only dependency on standard APIs (javax). And the code could also be used in another implementation e.g. of the JSR 330.

Here a simple code snippet, which shows how to use this three Java standards in a spring bean.

import javax.validation.constraints.NotNull;
public class Person {
@NotNull // JSR 303
private String name;
public String getName(){ return name; }
public void setName(String name){ this.name = name;}
}
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
@Named("personService") // JSR 330
public class PersonServiceImpl implements PersonService {
@Inject // JSR 330
Validator validator; // JSR 303
@PostConstruct // JSR 250
public void init() {
System.out.println("Do Init");
}
@PreDestroy // JSR 250
public void destroy() {
System.out.println("Do Init");
}
@Override
public void save(Person person) {
Set<ConstraintViolation<Person>> validate = validator.validate(person);
for (ConstraintViolation<Person> constraintViolation : validate)
System.out.println(constraintViolation.getMessage());
}
@Override
public boolean isValidTester(Person person){
Set<ConstraintViolation<Person>> validate = validator.validate(person);
return validate.isEmpty();
}
}


And here the spring context configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="demo" />
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</beans>

You could also mix the Spring annotations with the JSR 330 annotation. I think a good strategy is to use the JSR 330 annotation when every its possible and makes sense. In some cases you would use the spring specific annotations.

Which annotations do you prefer to use in a Spring application?

For more details see the spring documentation:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/