访问服务层和控制器中的spring用户 - Spring 3.2的任何更新?

时间:2013-01-14 21:01:04

标签: java spring spring-mvc

我想访问当前登录的用户,我这样做(来自静态方法)

public static User getCurrentUser() {

final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof User) {
  return (User) principal;
  }
}

或像这样注射和施法:

@RequestMapping(value = "/Foo/{id}", method = RequestMethod.GET)
public ModelAndView getFoo(@PathVariable Long id, Principal principal) {
        User user = (User) ((Authentication) principal).getPrincipal();
..

在用户实现用户详细信息的情况下,两者看起来有点蹩脚在Spring 3.2中有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

我不认为spring 3.2为此目的有新内容。您是否考虑过使用自定义注释?

这样的事情:

带有自定义注释的控制器:

@Controller
public class FooController {

    @RequestMapping(value="/foo/bar", method=RequestMethod.GET)
    public String fooAction(@LoggedUser User user) {
        System.out.print.println(user.getName());
        return "foo";
    }
}

LoggedUser注释:

@Target(ElementType.PARAMETER)
@Retention(RententionPolicy.RUNTIME)
@Documented
public @interface LoggedUser {}

WebArgumentResolver:

public class LoggedUserWebArgumentResolver implements WebArgumentResolver {

    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        Annotation[] annotations = methodParameter.getParameterAnnotations();

        if (methodParameter.getParameterType().equals(User.class)) {
            for (Annotation annotation : annotations) {
                if (LoggedUser.class.isInstance(annotation)) {
                    Principal principal = webRequest.getUserPrincipal();
                    return (User)((Authentication) principal).getPrincipal();
                }
            }
        }
        return WebArgumentResolver.UNRESOLVED;
    }
}

豆类配置:

<bean id="loggedUserResolver" class="com.package.LoggedUserWebArgumentResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="customArgumentResolver" ref="loggedUserResolver" />
</bean>

答案 1 :(得分:0)

我创建了一个类似于静态的方法,但是将它放在一个新的spring bean中并将该bean注入到控制器(或其他层的对象)中,我需要在其中获取有关用户的信息。这样我就可以避免在测试依赖于静态的代码时出现的困难,并且所有使用SecurityContext的代码都很好地封装到我的bean中(就像你在静态中一样)

相关问题