简体   繁体   中英

Using Spring Factory bean pattern - no bean return null?

I am using Factory pattern in SPRING like in this example http://kh-yiu.blogspot.co.il/2013/04/spring-implementing-factory-pattern.html

In case that there is no bean with specific name I get exception org.springframework.beans.factory.NoSuchBeanDefinitionException

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'XXX' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:549)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.config.ServiceLocatorFactoryBean$ServiceLocatorInvocationHandler.invokeServiceLocatorMethod(ServiceLocatorFactoryBean.java:367)
    at org.springframework.beans.factory.config.ServiceLocatorFactoryBean$ServiceLocatorInvocationHandler.invoke(ServiceLocatorFactoryBean.java:356)
    at com.sun.proxy.$Proxy24.createManualDepositProcess(Unknown Source)

I get exceptions in case I try to get bean that not defined, like printStrategyFactory.getStrategy("NO_DEF").print(doc);

Is it possible in case that there is no bean - return null ? Thank you !

If you're autowiring as in the example you posted, @Autowired(required=false) should do the trick.

Edit: sorry for getting your question wrong at first, I just spotted the @Autowired annotation in the Test of the link you posted and thought of the standard solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM