在我的自定义注释中使用Spring属性@Value

时间:2019-11-17 09:45:56

标签: java spring-boot spring-security spring-test

伙计们,我有一个自定义批注,旨在在通过Spring安全性进行保护的Spring引导集成测试中模拟用户。

/**
 * Mock user for MVC authentication tests
 */
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockMyAppUserSecurityContextFactory.class, setupBefore = TestExecutionEvent.TEST_METHOD)
public @interface WithMockMyAppUser {

    long tokenExpMillis() default 36000L ;

    String[] roles() default {"NONE"};
}

这是它的用法:

@WithMockMyAppUser(roles={"ADMIN"})
class AddressServiceTest {
...
}

我的问题是,有可能使用Spring属性@Value以某种方式提供角色,而不仅仅是在"ADMIN"处硬编码@WithMockMyAppUser(roles={"ADMIN"})字符串吗?

1 个答案:

答案 0 :(得分:0)

您可以做的是扩展@WithMockMyAppUser

public @interface WithMockCustomUser {
    ...
    String rolesProprety() default "";

然后您可以在如下测试中使用它:

@WithMockMyAppUser(rolesProprety = "${test.roles}")

为了完成这项工作,您将必须将ConfigurableListableBeanFactory bean自动连接到WithMockMyAppUserSecurityContextFactory中并利用其resolveEmbeddedValue方法:

public class WithMockMyAppUserSecurityContextFactory
        implements WithSecurityContextFactory<WithMockMyAppUser> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    ...

    String[] getRoles(WithMockMyAppUser user){
        if (user.roles().length > 0) {
            return user.roles();
        }
        if (user.rolesProprety() != null) {
            String roleStr = factory.resolveEmbeddedValue(user.rolesProprety());
            if (roleStr != null && roleStr.length() > 0)
            return roleStr.split(",");
        }
        return new String[0];
    }
}

首先,检查是否提供了硬编码的角色,并在这种情况下将其返回,否则尝试解决rolesProperty