调用 Spring 个 bean 的函数接口

Function Interfaces calling Spring beans

我想映射特定类型以触发 Spring 方法,

我按键保存函数接口映射,函数将调用 Spring 服务方法,但我有一个问题,它必须是静态的,例如:

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

所以我的方法必须是静态的

 public static boolean myTypeMethod(User user)

我是否应该静态加载 Spring bean 以调用静态方法:

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

或者没有静态初始化Spring beans 有更好的吗?

我会在定义您的 Map 的 Bean 上使用 Spring 的 InitializingBean 接口。 然后你 @Autowire 你的 MySpringService 在你的 bean 中。

最后,在 afterPropertiesSet() 方法中,放置您的 Map 初始化代码,但使用 Autowired MySpringService 代替注册您的方法调用,因此您不需要调用 Spring 来自静态上下文的 bean。