2015-05-18 1 views
0

У меня есть следующая xml-конфигурация в моем контекстном контексте xml, я очень мало использовал аннотационный подход и не смог понять, как представлять следующее, используя аннотацию, нужна помощь.как преобразовать нотацию xml в нотацию на основе аннотаций: Spring - Java

<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> 

В моей Java класс (менеджер политики) он называется следующим образом, я на самом деле в виду образец и пытается преобразовать его все аннотацию baesed.

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

EDIT: Я попытался создать компонент для org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails, но не знаете, как установить его свойства и как получить к нему доступ, как конструктор арг к myPolicyAdminTemplate

ответ

3

Вы можете настроить то же самое бобы с использованием JavaConfig следующим образом:

@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; 
    } 
} 
1

Чтобы установить реквизит из фасоли можно использовать либо @Value во время строительства:

How to inject a value to bean constructor using annotations

и это одна:

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

Или @Value в переменных. Вы также можете использовать @Resource, но я бы не рекомендовал его.

В вашем случае, конструктор для org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails

Было бы вроде как

@Autowired 
public ResourceOwnerPasswordResourceDetails(
    @Value("${accessTokenEndpointUrl}") String accessTokenUri, 
    @Value("${clientId}") String clientId, 
    @Value("${clientSecret}") String clientSecret, 
    @Value("${policyAdminUserName}") String username, 
    @Value("${policyAdminUserPassword}") String password 
) 
0

Я дам вам конфигурацию XML с ее эквивалентной конфигурацией на основе аналогов re ветственно, так что вы легко увидеть, как изменить компонент из XML в Java и наоборот

<?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> 

этот файл с именем springrest-sevlet. на самом деле вы можете дать имя, которое вы хотите затем «-servlet» и указать это имя в файле 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> 

два файла должны быть места в папке «WEB-INF».

Теперь эквивалентно конфигурации на основе эту заметку

/* 
     * 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(); 
      } 

     } 

этот файл должен сопровождаться одной этой

 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[]{"/"}; 
      } 

     } 
Смежные вопросы