Search code examples
javaspringspring-annotations

how to convert xml notation to annotation based notation : Spring - Java


I have following xml configuration in my spring context xml, I have used annotation based approach very less and unable to figure out how to represent following using annotation, need help.

<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
        <constructor-arg>
            <bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
                <property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
                <property name="clientId" value="${clientId}" />
                <property name="clientSecret" value="${clientSecret}" />
                <property name="username" value="${policyAdminUserName}" />
                <property name="password" value="${policyAdminUserPassword}" />
            </bean>
        </constructor-arg>
    </bean>

In my java class(Policy manager) it is referred as following, I am actually referring a sample and trying to convert it all annotation baesed.

@Autowired
@Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;

EDIT: I tried creating a bean for org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails but not sure how to set its properties and how to access it as constructor args to myPolicyAdminTemplate


Solution

  • You can configure the same beans using JavaConfig as follows:

    @Component
    @Configuration
    public class AppConfig
    {
        @Value("${accessTokenEndpointUrl}") String accessTokenUri;
        @Value("${clientId}") String clientId;
        @Value("${clientSecret}") String clientSecret;
        @Value("${policyAdminUserName}") String username;
        @Value("${policyAdminUserPassword}") String password;
    
        @Bean
        public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
        {
            return new OAuth2RestTemplate(details);
        }
    
        @Bean
        public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
        {
             ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
             bean.setAccessTokenUri(accessTokenUri);
             bean.setClientId(clientId);
             bean.setClientSecret(clientSecret);
             bean.setUsername(username);
             bean.setPassword(password);         
             return bean;
        }
    }