簡體   English   中英

在我的自定義注釋中使用 Spring 屬性 @Value

[英]Use Spring property @Value inside my custom annotation

伙計們,我有一個自定義注釋,旨在在 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來提供角色,而不僅僅是在@WithMockMyAppUser(roles={"ADMIN"})中硬編碼"ADMIN"字符串?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM