Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make @Resource optional?

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.

like image 804
MrProper Avatar asked May 15 '13 08:05

MrProper


People also ask

Should I use @resource or @autowired?

@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).

What is difference between @autowired and @resource in spring?

@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.


2 Answers

ok looks like it isn't possible. Had to use @Autowired(required = false). Not what I exactly wanted, but it will do.

like image 103
MrProper Avatar answered Oct 28 '22 04:10

MrProper


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.

like image 41
gpeche Avatar answered Oct 28 '22 03:10

gpeche