Java 在自定义注释中使用Spring属性@Value
伙计们,我有一个定制的注释,旨在模拟Spring引导集成测试中的用户,该测试由Spring security保护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
/**
* 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