Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Interfaces calling Spring beans

I want to map specific types to trigger Spring methods,

I save Map of Function Interfaces by key, the functions will call Spring services method, but I have an issue that it must be static, e.g.:

 private Map<Pair<Type, Boolean>, Function<User, Boolean>> functionInterfaces = new HashMap<>();
 {
    functionInterfaces .put(Pair.of(Type.MY_TYPE, Boolean.TRUE), MySpringService::myTypeMethod);
 }

So my method must be static

 public static boolean myTypeMethod(User user)

Should I load Spring bean statically in order to call static method:

private static final MySpringService mySpringService = ApplicationInitializer.getAppContext().getBean(MySpringService.class);

Or is there a better without static initializing Spring beans?

like image 310
user7294900 Avatar asked Jun 25 '26 13:06

user7294900


1 Answers

I'd use Spring's InitializingBean interface on the Bean where your Map is defined. Then you @Autowire your MySpringService in your bean.

Finally, in the afterPropertiesSet() method, place your Map initializing code, but use the Autowired MySpringService instead to register your method call, so you don't need to call Spring bean from a static context.

like image 187
Xavier Gourmandin Avatar answered Jun 28 '26 01:06

Xavier Gourmandin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!