3

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?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Possibly relevant: [Spring static initialization of a bean](https://stackoverflow.com/q/4247705/2402272). – John Bollinger Jan 21 '19 at 14:25
  • @JohnBollinger but I need currently to call bean from static context – Ori Marko Jan 21 '19 at 14:27
  • 4
    Calling Spring beans from static context is pointless, as you're losing all the benefits of dependency injection. Why static context? I think you have another problem, bigger than this one. Please explain all the problem, so that users can help you better. – fps Jan 21 '19 at 15:17
  • @FedericoPeraltaSchaffner I want to call different methods using context based on type/enum key and boolean toggle . But it's too general question.no? – Ori Marko Jan 21 '19 at 16:18
  • @user7294900 are all these methods in the same class? Are they instance methods? Do they have the same signature? Why do you need this functionality at all? – fps Jan 21 '19 at 16:23

1 Answers1

2

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.

Xavier
  • 66
  • 1
  • 6
  • Can you link to docs or example of `afterPropertiesSet()` is it same as using `@PostConstruct` method? – Ori Marko Jan 21 '19 at 14:53
  • Sure, I'm not sure about a similarity with `@PostContruct`. Check [here](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/InitializingBean.html#afterPropertiesSet--) – Xavier Jan 21 '19 at 16:05
  • I also change to using non static `this::myTypeMethod` – Ori Marko Jan 22 '19 at 06:56