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

问题描述 投票:3回答:1

伙计们,我有一个自定义注释,旨在在受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"})字符串吗?

java spring-boot spring-security spring-test
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.