根据类获取bean

  • ContextHolder:
    public class ContextHolder {
        /**
         * 可使用{@link org.springframework.context.ApplicationContextAware}接口
         */
        private static ApplicationContext context;
    
        public static ApplicationContext getContext() {
            return context;
        }
    
        public static void setContext(ApplicationContext context) {
            ContextHolder.context = context;
        }
    }
  • 获取bean
private UserService userService;
if (userService == null) {
    userService = (UserService) ContextHolder.getContext().getBean(UserService.class);
}

你可能感兴趣的:(spring)