Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在自定义注释中使用Spring属性@Value_Java_Spring Boot_Spring Security_Spring Test - Fatal编程技术网

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

Java 在自定义注释中使用Spring属性@Value,java,spring-boot,spring-security,spring-test,Java,Spring Boot,Spring Security,Spring Test,伙计们,我有一个定制的注释,旨在模拟Spring引导集成测试中的用户,该测试由Spring security保护 /** * Mock user for MVC authentication tests */ @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockMyAppUserSecurityContextFactory.class, setupBefore = TestExecutionEv

伙计们,我有一个定制的注释,旨在模拟Spring引导集成测试中的用户,该测试由Spring security保护

/**
 * 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”})

您可以做的是扩展
@WithMockMyAppUser

public @interface WithMockCustomUser {
    ...
    String rolesProprety() default "";
然后您可以在以下测试中使用它:

@WithMockMyAppUser(rolesProprety = "${test.roles}")
为了实现这一点,您必须使用MockMyAppUserSecurityContextFactory将
ConfigurableListableBeanFactory
bean自动连接到
中,并使用其
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];
    }
}
带有MockMyAppUserSecurityContextFactory的公共类
使用SecurityContextFactory实现{
@自动连线
可配置列表工厂;
...
字符串[]getRoles(WithMockMyAppUser用户){
if(user.roles().length>0){
返回user.roles();
}
if(user.rolesproperty()!=null){
字符串roleStr=factory.resolveEmbeddedValue(user.rolesproperty());
if(roleStr!=null&&roleStr.length()>0)
返回角色拆分(“,”);
}
返回新字符串[0];
}
}
首先,检查角色是否是硬编码的,并在这种情况下返回它们,否则尝试解析
rolesProperty