Junior — Middle
What needs to be done to prevent a program from crashing if a specific Bean is missing in the Spring context?
sobes.tech AI
Answer from AI
To prevent a program failure when a specific Bean is missing in the Spring context, you can use the @Autowired annotation with the parameter required = false. This allows Spring not to throw an exception if the required Bean is not found, but simply set the field to null.
Example:
@Autowired(required = false)
private MyBean myBean;
You can also use @Nullable or Optional<MyBean> for more explicit handling of a missing Bean.
If the Bean is only needed under certain conditions, you can use profiles or conditional annotations (@ConditionalOnMissingBean, @ConditionalOnBean) for flexible component creation management.