How to make @Resource optional?

Is there a way to make @Resource optional? This means that if I don't have the bean type requested by @Resource, I will not get an Exception, but it will just be set to null.

+7
source share
2 answers

ok it seems like this is impossible. Had to use @Autowired (required = false). Not what I definitely wanted, but he will do.

+2
source

You can use a custom factory bean for this:

public class OptionalFactoryBean<T> implements BeanFactoryAware, FactoryBean<T> { private String beanName; public void setBeanName(String beanName) { this.beanName = beanName; } @Override public T getObject() throws Exception { T result; try { result = beanFactory.getBean(beanName); } catch (NoSuchBeanDefinitionException ex) { result = null; } return result; } private BeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } private Class<?> objectType = Object.class; public void setObjectType(Class<?> objectType) { this.objectType = objectType != null? objectType : Object.class; } @Override public Class<?> getObjectType() { return objectType; } @Override public boolean isSingleton() { return true; } } 

Spring for your optional bean will be:

 <bean id="myBean" class="mypackage.OptionalFactoryBean" scope="singleton"> <property name="beanName" value="myRealBean"/> <property name="objectType" value="mypackage.MyRealBean"/> </bean> 

And you will get null . Then you can define:

 <bean id="myRealBean" class="mypackage.MyRealBean" ...> <!-- .... --> </bean> 

if you want to enter some specific bean.

0
source

All Articles