Is there some way to make @Resource optional? This means if I don't have a bean of type requested by @Resource, I won't get Exception, but it would be just set to null.
@Resource is quite similar to @Autowired and @Inject, but the main difference is the execution paths taken to find out the required bean to inject. @Resource will narrow down the search first by name then by type and finally by Qualifiers (ignored if match is found by name).
@Autowired in combination with @Qualifier also autowires by name. The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.
ok looks like it isn't possible. Had to use @Autowired(required = false). Not what I exactly wanted, but it will do.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With