Thu 10 Aug 2006
Spring Recipe #1: Validating setter injected fields
Posted by dkaz under Java, Programming
Here’s a simple recipe I’ve used over and over (wherever auto-wiring constructors was inappropriate). Validating at container startup time is certainly better than relying on NPEs at runtime.
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class FooService implements InitializingBean {
private Dependency dependency;
public void afterPropertiesSet() throws IllegalArgumentException {
Assert.notNull(dependency, "Dependency cannot be null");
}
public void setDependency(Dependency dependency) {
this.dependency = dependency;
}
}

August 11th, 2006 at 12:17 pm
We do that feature sparingly… IMHO, extending a Spring interface creates an unnecessary direct relationship between your POJO code and the IoC container.
Perhaps the same functionality should be feasible using an external check or a mechanism that’s not explicitely Spring related such as annotations.
August 11th, 2006 at 12:45 pm
You might be interested in Spring’s @Required annotation support as described: here.
August 18th, 2006 at 11:06 am
We’re so heavily invested in Spring, that service interface dependencies on Spring are not a huge concern.
@Required would also introduce that dependency, wouldn’t you say?
August 18th, 2006 at 4:58 pm
No… it’s definitely not a huge concern. And you’re right about the @Required implmentation. However, the @Required seems more flexible since it can be used at more stages within Spring’s pojo lifecycles. A more generic @Required annotation would be even nicer.
I wonder if a contract-by-design approach would work better…