在我的自定义注释中使用 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
提供角色,而不是只在此处硬编码 "ADMIN"
字符串 @WithMockMyAppUser(roles={"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];
}
}
首先,检查角色是否以硬编码方式提供,在这种情况下 return 它们,否则尝试解析 rolesProperty
.
伙计们,我有一个自定义注释,旨在模拟 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"})
?
你可以做的是扩展 @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];
}
}
首先,检查角色是否以硬编码方式提供,在这种情况下 return 它们,否则尝试解析 rolesProperty
.