0

Here're my use case:

When my app launched, N beans of type A will be created.

I'd like to have my own biz logic to check these N beans 1 by 1 and:

  • if none of them satisfy my criteria, I'll create another bean of type A to spring container.

  • if any of them satisfy my criteria, just do nothing.

I'm not sure whether I can simply use Optional like this:

@Autowired
List<A> beans;

@Bean
public Optional<A> maybeA(){
  //check beans and optionally create a A
}
Roland Weisleder
  • 9,668
  • 7
  • 37
  • 59
anuni
  • 889
  • 10
  • 26
  • Check for `GenericBeanDefinition` https://stackoverflow.com/questions/48537481/spring-dynamic-bean-creation-depending-on-other-bean – ridvanzoro Sep 03 '18 at 06:53
  • You could annotate `maybeA` with `@Conditional`. But this case you only have access to the bean definitions, not the bean instances itself. See https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Conditional.html – Roland Weisleder Sep 03 '18 at 07:28

1 Answers1

0

Defining bean that returns type Optional is very unusual and not a good solution.I suggest you check if you could implement your logic as described https://iamninad.com/conditional-bean-creation-in-spring-boot/ or if you insist to follow your solution, you can create a new class as :

public class UnMatchedACriteriaImpl implements A {

   public void testMethod() throws UnSatisfiedXCriteria {
       throw new UnSatisfiedXCriteria();
   }
}

and change your bean definition to :

@Bean
public A maybeA(){
  //check beans and optionally create a A
}

When you criteria does not match you return UnMatchedACriteriaImpl version of A. which is clear and manageable when you want to use it in your application.