Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Spring property @Value inside my custom annotation

Guys I have a custom annotation which is designed to Mock the user in Spring boot integration tests which are secured with 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"};
}

And here is the usage of that:

@WithMockMyAppUser(roles={"ADMIN"})
class AddressServiceTest {
...
}

My question is, is that possible to somehow provide the roles using Spring property @Value instead of just having hardcoded "ADMIN" string here @WithMockMyAppUser(roles={"ADMIN"}) ?

like image 686
Arsen Alexanyan Avatar asked Dec 03 '25 18:12

Arsen Alexanyan


1 Answers

What you could do is to extend @WithMockMyAppUser

public @interface WithMockCustomUser {
    ...
    String rolesProprety() default "";

Then you could use it in tests like following:

@WithMockMyAppUser(rolesProprety = "${test.roles}")

In order to make this work you would have to autowire a ConfigurableListableBeanFactory bean into your WithMockMyAppUserSecurityContextFactory and utilize its resolveEmbeddedValue method:

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];
    }
}

First, check if the roles were provided hardcoded and return them in that case, otherwise try to resolve the rolesProperty.

like image 187
pero_hero Avatar answered Dec 06 '25 07:12

pero_hero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!