我在Spring Security 3.1中使用Spring 3.1.0.RELEASE.我想将我的Spring用户(即当前登录的用户)注入控制器.我想这样做而不是使用
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
因为它允许我使用JUnit更轻松地测试控制器.但是,我的当前设置有问题.我的问题是,将我的用户(每个请求)注入我的控制器的正确方法是什么?在我的应用程序上下文文件中,我有……
在哪里我将工厂类定义为……
public class SecurityHolder {
@Autowired
private static UserService userService;
public static MyUserDetails getUserDetails() {
final Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
final MyUserDetails reg = (MyUserDetails) a.getPrincipal();
final int userId = reg.getId();
final MyUserDetails foundUser = userService.findUserById(userId);
return foundUser;
} // if
} // getUserDetails
}
但工厂类反复死亡,因为“userService”无法自动装配(值始终为null).我正在寻找一种更好的方法来完成所有这些,也可以轻松地集成到我的JUnit测试中.有任何想法吗?
编辑:这是我正在寻找的JUnit测试……
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "file:src/test/resources/testApplicationContext.xml" })
public class UserEventFeedsControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
...
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@Before
public void setUp() {
...
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
...
@Test
public void testSubmitUserEventFeedsForm() throws Exception {
request.setRequestURI("/eventfeeds.jsp");
request.setMethod("POST");
final List
最佳答案
您无法自动装配静态字段.有一些解决方法,但我不想向你展示……
原文链接:https://www.f2er.com/spring/431633.html有很多方法可以更轻松,更优雅地访问当前用户:
>将Principal注入控制器(参见When using Spring Security,what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?):
public ModelAndView showResults(final HttpServletRequest request,Principal principal) {
final String currentUser = principal.getName();
UserDetails ud = ((Authentication)principal).getPrincipal()
>通过SecurityContext开发自定义facade
>替换SecurityContextHolder中的内置contextHolderStrategy以进行测试
也可以看看
> How to get active user’s UserDetails
> Spring 3 MVC Controller integration test – inject Principal into method