我想映射特定类型来触发 Spring 方法,
我按键保存函数接口(interface)映射,函数将调用 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 bean有更好的吗?
最佳答案
我将在定义 Map 的 Bean 上使用 Spring 的 InitializingBean
接口(interface)。
然后你在你的bean中@Autowire
你的MySpringService
。
最后,在 afterPropertiesSet()
方法中,放置您的 Map 初始化代码,但使用 Autowired MySpringService
来注册您的方法调用,因此您不需要从静态上下文调用 Spring bean。
关于java - 调用 Spring bean 的函数接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291835/