Spring reference null bean
I'm pretty sure that Spring won't allow you to associate null with a bean id or alias. You can handle this by setting properties to null. In Spring 3. For anyone coming to this question, keep in mind that simply setting the Autowired annotation as optional will do the trick i. Spring will leave the reference null if no qualifying bean is found.
Note that you would have to do this everywhere the bean is referenced, which may be a bigger hassle than creating a null-factory as mentioned above.
Some noted above, axtact's answer doesn't work in Autowiring contextes, where Spring will rely on correct information from the getObjectType method.
So you might end up with errors like:. So here's a small variation which involves allowing users to force the objectype at construction. Using a property instead of a constructor-arg didn't work because Spring doesn't fully initialize the beans in this context.
For anyone else who comes across this: another approach if you're using Java 8 is to use the Supplier functional interface to wrap a potentially null bean:. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams?
Collectives on Stack Overflow. Learn more. Intentionally setting a Spring bean to null Ask Question. Asked 11 years, 11 months ago. Active 2 years, 9 months ago. Viewed 52k times. Improve this question. Honza Zidek 7, 4 4 gold badges 59 59 silver badges 94 94 bronze badges. Lunikon Lunikon 3, 4 4 gold badges 21 21 silver badges 20 20 bronze badges.
Add a comment. Active Oldest Votes. Here's how you did this in Spring 2. Improve this answer. Stephen C Stephen C k 90 90 gold badges silver badges bronze badges. I much prefer this solution; it does not necessitate the creation of a custom factory bean — Richard. Great catch! I had a Spring Configuration class containing a method returning a Bean. But the method does a few checks before returning an instance. When the checks fail, it returns null and it caused UnsatisfiedDependencyException — asgs.
Marijn 9, 5 5 gold badges 53 53 silver badges 76 76 bronze badges. There's an open feature request for this, but's been sitting there for 2 years This didn't work for me if I used the bean in an Autowired context. Collectives on Stack Overflow. Learn more. Spring bean definition null reference Ask Question. Asked 9 years ago. Active 8 years, 11 months ago.
Viewed 3k times. Improve this question. Add a comment. Active Oldest Votes. Improve this answer. Just don't do anything. Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password.
Post as a guest Name. Email Required, but never shown.
0コメント