Skip to content

Instantly share code, notes, and snippets.

@nacx
Created January 14, 2011 09:08
Show Gist options
  • Save nacx/779389 to your computer and use it in GitHub Desktop.
Save nacx/779389 to your computer and use it in GitHub Desktop.
Spring injection by name example
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
public abstract class InjectableProperty implements InitializingBean, ApplicationContextAware
{
private String beanName;
private ApplicationContext context;
@Override
public void afterPropertiesSet() throws Exception
{
Assert.notNull(beanName, "beanName must not be null");
if (context.containsBean(beanName))
{
setBean(context.getBean(beanName));
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException
{
this.context = applicationContext;
}
protected abstract void setBean(Object bean);
}
public class MyClass extends InjectableProperty
{
private Object property;
@Override
protected void setBean(Object bean)
{
property = bean;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment