Marker interfaces are an efficient method of injecting Spring dependencies. By implementing a marker interface, a bean tells the Spring container that it wishes to be injected with a dependency. An example from the Spring core is MessageSourceAware, shown below:
public interface MessageSourceAware {
void setMessageSource(MessageSource messageSource);
}
Any bean that implements MessageSourceAware will be automatically injected with a MessageSource after the bean is constructed.
To do this for your own classes, begin by creating an appropriate marker interface:
public interface FooAware {
void setFoo(Foo foo);
}
Then, create a class that implements BeanPostProcessor. Spring spots beans that implement this interface and allows them an opportunity to fiddle with beans after they are constructed, but before they are made available to other beans. We also implement ApplicationContextAware, which is a marker interface that provides us with access to the application context.
public class MarkerInterfaceProcessor implements BeanPostProcessor,
ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
if (bean instanceof FooAware) {
((FooAware) bean).setFoo(applicationContext
.getBean(Foo.class));
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
// We have no need to adjust the bean after initialization
return bean;
}
@Override
public void setApplicationContext(
ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
}
A single class can be used to inject all the marker interface dependencies in your project – just add additional instanceof clauses. The final step is to tell Spring that your MarkerInterfaceProcessor class exists. There is no need to give the bean an id or a name, just declaring it is sufficient:
<bean class="com.foo.MarkerInterfaceProcessor" />

