在请求范围内使用工厂方法自动装配

时间:2011-10-29 16:43:29

标签: java spring spring-mvc spring-security

我正在尝试对我的Spring应用程序进行单元测试。 使用Spring-Security,我很难模仿SecurityContext来对我的控制器进行单元测试。

我发现了以下问题:Unit testing with Spring Security

我正试图在我的网络应用程序上使用“社区维基”答案(目前第二个答案)。

我主要使用注释驱动的开发,然后我有以下内容:

MainController.java

@Controller
public class MainController {

    private User currentUser;

    @Autowired
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

    ...

}

UserFactory.java

@Component
public class UserFactory {

    @Bean
    public User getUserDetails() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        if (a == null) {
            return null;
        } else {
            return (User) a.getPrincipal();
        }
    }
}

User.java

public class User implements UserDetails {

    private long userId;
    private String username;
    private String password;
    private boolean enabled;
    private ArrayList<GrantedAuthority> authorities;

    public User() {

    }

    ...

}

问题是getUserDetails()方法似乎从未被调用过,UserFactory从未使用过。 (我尝试过System.out.println,我尝试了调试器)

但是没有关于MainController在运行时或任何请求都没有连线的错误。

属性currentUser似乎是alaways null。

我也没有找到满足我需求的东西来查看这个问题:problem in Spring session scope bean with AOP

这是我的第一个春季网络应用程序,请不要苛刻。 :)

1 个答案:

答案 0 :(得分:4)

我注意到的第一件事是你把@Scope放在错误的地方。它应该采用@Bean方法,而不是@Autowired方法,即

@Autowired
public void setCurrentUser(User currentUser) {

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public User getUserDetails() {

我很惊讶春天并没有抱怨这一点。