【问题标题】:Use Spring property @Value inside my custom annotation在我的自定义注释中使用 Spring 属性 @Value
【发布时间】:2019-11-17 09:45:56
【问题描述】:

伙计们,我有一个自定义注释,旨在在 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】:

    你可以做的是扩展@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

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2011-09-19
      • 2014-11-28
      相关资源
      最近更新 更多