Skip to content

Instantly share code, notes, and snippets.

@odrotbohm
Created April 26, 2012 11:33
Show Gist options
  • Save odrotbohm/2498969 to your computer and use it in GitHub Desktop.
Save odrotbohm/2498969 to your computer and use it in GitHub Desktop.
Optional and mandatory dependencyies in a Spring component
public interface MyComponent {
void myBusinessMethod(Parameter parameter);
}
/**
* Package protected implementation to avoid clients to use it directly. It contains
* a mandatory and optional dependency where the mandatory one is exposed as constructor
* argument and checked to be not {@literal null}. The optional dependency can be either
* {@literal null} or set from the outside. It's also fine to default this dependency to
* something but one has to adapt the setter then.
*
* Using this design principle it becomes immediately obvious what dependencies are
* mandatory (constructor arguments, final fields) and which are optional (setters and
* non final fields) and have to be checked against {@literal null} before invocation.
*
* @author Oliver Gierke
*/
@Component
class MyComponentImplementation implements MyComponent {
private final MandatoryDependency mandatoryDependency;
private OptionalDependency optionalDependency;
@Autowired
public MyComponentImplementation(MandatoryDependency dependency) {
Assert.notNull(dependency, "Mandatory dependency must be given!");
this.mandatoryDependency = dependency;
}
@Autowired(required = false)
public void setOptionalDependency(OptionalDependency dependency) {
this.optionalDependency = dependency;
}
@Override
public void myBusinessMethod(Parameter parameter) {
if (optionalDependency != null) {
// … do something if optional dependency is set
}
// Mandatory dependency can be used without null check
mandatoryDependency.callSomeMethod(…);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment