Skip to content

Instantly share code, notes, and snippets.

@devvesa
Forked from nacx/SpringInjectionExample.java
Created October 7, 2012 17:35
Spring injection by name
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