非实用静态方法

non utility static methods

我有一个方法可以从 springsecuritycontext 对象中提取登录用户的详细信息。

我读到只有实用方法(进行某些计算)应该是静态的。

这是我的方法,它似乎不是一个实用方法,但我没有找到任何理由为什么我不应该将它设为静态,因为我在多个 bean 中使用它

public static int getSignedUpUser()
    {
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if(ctx != null)
        {
            final Authentication auth = ctx.getAuthentication();

            if(auth != null)
            {
                final Object principal = auth.getPrincipal();


                if(principal instanceof AUser)
                {
                    final AUser au = (AUser)principal;
                    return au.getId();
                }
            }
        }

        return 0;
    }
}

概念上显示的方法实现是 class 实例的一部分。这就是为什么操作可以是静态的。所以我更喜欢使用 instane 而不是 tahn 静态方法。

简而言之:使用静态方法即可。

当我们说静态方法应该是实用方法时,我们是在谈论静态方法应该是线程安全的。

让我们看看 SecurityContextHelper.getContext() 方法。它是这样实现的:

private static SecurityContextHolderStrategy strategy;

public static SecurityContext getContext() {
    return strategy.getContext();
}

请注意,它 returns 来自静态变量 strategy 的上下文。所以 strategy 必须保持线程安全。

SecurityContextHolderStrategy接口有三种实现:

其中两个是线程本地的,另一个有一个private static SecurityContext contextHolder;

那我们看看SecurityContextHolder.initialize()方法:

private static void initialize() {
    if ((strategyName == null) || "".equals(strategyName)) {
        // Set default
        strategyName = MODE_THREADLOCAL;
    }

    if (strategyName.equals(MODE_THREADLOCAL)) {
        strategy = new ThreadLocalSecurityContextHolderStrategy();
    } else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
        strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
    } else if (strategyName.equals(MODE_GLOBAL)) {
        strategy = new GlobalSecurityContextHolderStrategy();
    } else {
        // Try to load a custom strategy
        try {
            Class<?> clazz = Class.forName(strategyName);
            Constructor<?> customStrategy = clazz.getConstructor();
            strategy = (SecurityContextHolderStrategy) customStrategy.newInstance();
        } catch (Exception ex) {
            ReflectionUtils.handleReflectionException(ex);
        }
    }

    initializeCount++;
}

这表明MODE_THREADLOCAL是默认策略。甚至 GlobalSecurityContextHolderStrategy 也使用静态上下文持有者。所以你可以在静态方法中使用它们。

你问问题的方式不对。如果您查看 getSignedUpUser 的方法,您会看到 class 它是其中的一部分。你的问题应该是这样的:

Who gets the signed up user? An instance, or all the instances collectively (the class)?

static 成员或方法是集体成员或方法。比如鸟的数量,就是关于鸟的一个集合数据,是static。非静态成员或方法是独立的。例如,一只鸟有一个重量,它与这只鸟单独关联。