How do you make @Resource optional?
You can use @Value
and default value (#{null}
) on Resource type.
@Value("some-data.txt:#{null}") Resource resource
If file some-data.txt does not exist property isn't set as null
but a resource with a non-existing file. You can call resource.exists()
instead of resource != null
.
public ResourceExample(@Value("some-data.txt:#{null}") Resource resource) {
if (resource.exists()) {
something(resource.getFile());
}
}
You should be able to use a custom factory bean to achieve 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 configuration for your optional bean would be:
<bean id="myBean" class="mypackage.OptionalFactoryBean" scope="singleton">
<property name="beanName" value="myRealBean"/>
<property name="objectType" value="mypackage.MyRealBean"/>
</bean>
And you would get null
injected. Then you could define:
<bean id="myRealBean" class="mypackage.MyRealBean" ...>
<!-- .... -->
</bean>
if you wanted to inject some particular bean.
ok looks like it isn't possible. Had to use @Autowired(required = false). Not what I exactly wanted, but it will do.