2

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

dev2d
  • 4,245
  • 3
  • 31
  • 54

3 Answers3

7

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;
    }
}
K. Siva Prasad Reddy
  • 11,786
  • 12
  • 68
  • 95
1

To set the props of a bean you can either use @Value during construction:

How to inject a value to bean constructor using annotations

and this one:

Spring: constructor injection of primitive values (properties) with annotation based configuration

Or @Value in the variables. You could also actually use @Resource, but I wouldn't recommend it.

In your case, the constructor for the org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails

Would be kinda like

@Autowired
public ResourceOwnerPasswordResourceDetails(
    @Value("${accessTokenEndpointUrl}") String accessTokenUri,
    @Value("${clientId}") String clientId,
    @Value("${clientSecret}") String clientSecret,
    @Value("${policyAdminUserName}") String username,
    @Value("${policyAdminUserPassword}") String password
)
Community
  • 1
  • 1
Nikola Yovchev
  • 9,498
  • 4
  • 46
  • 72
1

I shall give you a XML configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa

    <?xml version="1.0" encoding="UTF-8"?>

        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:context="http://www.springframework.org/schema/context"
               xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:p="http://www.springframework.org/schema/p"
               xsi:schemaLocation="
                http://www.springframework.org/schema/beans    
                http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.0.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

            <context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
            <mvc:annotation-driven />
            <bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/> 
            <bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>

            <!-- couche de persistance JPA -->
            <bean id="entityManagerFactory"
                  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
                <property name="dataSource" ref="dataSource" />
                <property name="jpaVendorAdapter">
                    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">            
                        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                        <property name="generateDdl" value="true" />
                        <property name="showSql" value="true" />
                    </bean>
                </property>
                <property name="loadTimeWeaver">
                    <bean
                        class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
                </property>
            </bean>

            <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
                <property name="locations" value="classpath:bd.properties"/>
            </bean>

            <!-- la source de donnéees DBCP -->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
                <property name="driverClassName" value="${bd.driver}" />
                <property name="url" value="${bd.url}" />
                <property name="username" value="${bd.username}" />
                <property name="password" value="${bd.password}" />
            </bean>

            <!-- le gestionnaire de transactions -->

            <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory" />
            </bean>


            <!-- traduction des exceptions -->
            <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

            <!-- annotations de persistance -->
            <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


        </beans> 

this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml

     <web-app> 
             <display-name>Gescable</display-name> 
             <servlet> 
                 <servlet-name>springrest</servlet-name> 
                 <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> 
                 <load-on-startup>1</load-on-startup> 
             </servlet> 
             <servlet-mapping> 
                 <servlet-name>springrest</servlet-name> 
                 <url-pattern>/</url-pattern> 
             </servlet-mapping> 
         </web-app>

the two files should be place in the folder "WEB-INF".

Now the equivalent with anotation based config

    /*
         * To change this license header, choose License Headers in Project Properties.
         * To change this template file, choose Tools | Templates
         * and open the template in the editor.
         */
        package com.mycompany.backendhibernatejpaannotation.configuration;

        import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
        import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
        import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
        import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
        import javax.sql.DataSource;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
        import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
        import org.springframework.jdbc.datasource.DriverManagerDataSource;
        import org.springframework.orm.jpa.JpaTransactionManager;
        import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
        import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
        import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
        import org.springframework.web.servlet.config.annotation.EnableWebMvc;

        /**
         *
         * @author vivien saa
         */
        @Configuration
        @EnableWebMvc
        @ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
        public class RestConfiguration {

            @Bean
            public IAbonneDao iAbonneDao() {
                return new AbonneDaoImpl();
            }

            @Bean
            public IAbonneService iAbonneService() {
                return new AbonneServiceImpl();
            }

        //    @Bean
        //    public PropertyPlaceholderConfigurer placeholderConfigurer() {
        //        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        //        placeholderConfigurer.setLocations("classpath:bd.properties");
        //        return placeholderConfigurer;
        //    }

            @Bean
            public DataSource dataSource() {
                DriverManagerDataSource dataSource = new DriverManagerDataSource();
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
                dataSource.setUsername("root");
                dataSource.setPassword("root");
                return dataSource;
            }

            @Bean
            public HibernateJpaVendorAdapter jpaVendorAdapter() {
                HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
                jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
                jpaVendorAdapter.setGenerateDdl(true);
                jpaVendorAdapter.setShowSql(true);
                return jpaVendorAdapter;
            }

            @Bean
            public InstrumentationLoadTimeWeaver loadTimeWeaver() {
                InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
                return loadTimeWeaver;
            }

            @Bean
            public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
                LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
                entityManagerFactory.setDataSource(dataSource());
                entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
                entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
                return entityManagerFactory;
            }

            @Bean
            public JpaTransactionManager jpaTransactionManager() {
                JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
                jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
                return jpaTransactionManager;
            }

            @Bean
            public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
                return new PersistenceExceptionTranslationPostProcessor();
            }

            @Bean
            public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
                return new PersistenceAnnotationBeanPostProcessor();
            }

        }

this file must be accompanied by this one

        package com.mycompany.backendhibernatejpaannotation.configuration;

        import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

        /**
         *
         * @author vivien saa
         */
        public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

            @Override
            protected Class<?>[] getRootConfigClasses() {
                return new Class[]{RestConfiguration.class};
            }

            @Override
            protected Class<?>[] getServletConfigClasses() {
                return null;
            }

            @Override
            protected String[] getServletMappings() {
                return new String[]{"/"};
            }

        }
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Vivien SA'A
  • 727
  • 8
  • 16