Function Interfaces calling Spring beans

user7294900 :

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?

Xavier Gourmandin :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101893&siteId=1