将Spring XML转换为JavaConfig

时间:2016-01-20 21:36:29

标签: java xml spring spring-java-config

我想将以下spring bean从xml转换为javaconfig类:

<bean id="restTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
    <constructor-arg ref="resource"/>
    <property name="messageConverters">
        <list>
            <ref bean="jaxbMessageConverter" />
            <ref bean="stringHttpMessageConverter" />
            <ref bean="jsonConverter" />
        </list>
    </property>
</bean>

<bean id="resource" class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
    <property name="username" value="asdfasdf" />
    <property name="password" value="asdfasdfa" />
    <property name="clientId" value="asdfasdf-asdfas-asdfasf" />
    <property name="clientSecret" value="asdfasdf-asdfasdf-adfasdfd" /> 
    <property name="accessTokenUri" value="asdfsadfasd" />
    <property name="grantType" value="password"></property>
    <property name="clientAuthenticationScheme" value="form" />
</bean>

你究竟如何转换这个?我遇到了this example,但这有点令人困惑,因为对我来说,<constructor-arg...><property....>标记在java中是如何表示的并不合理。在示例中,它们都转换为:

return new JButton(...);

1 个答案:

答案 0 :(得分:1)

在spring配置文件中,您需要执行以下操作:

@Bean
public ResourceOwnerPasswordResourceDetails resource() {
       ResourceOwnerPasswordResourceDetails  r = new ResourceOwnerPasswordResourceDetails ();
       r.setUsername("asdfasdf");
    ....

}
@Bean
public OAuth2RestTemplate restTemplate() {
      OAuth2RestTemplate rest = new OAuth2RestTemplate(resource());
      rest.setMessageConverters(...);
      List<HttpMessageConverter<?>> messageConv = new ArrayList<HttpMessageConverter<?>>();
      messageConv.add(new MappingJackson2HttpMessageConverter());
      rest.setMessageConverters(messageConv);
}

从上面的例子中你可以理解规则:

  1. 属性可以使用setProperty ..
  2. 完成
  3. 构造函数arg实际上是构造函数中的参数
  4. 列表是arraylist
  5. bean之间的依赖关系类似于示例

    建议:如果您正在努力实现某些目标,并且您不了解它只是谷歌并搜索具体示例..这将是最简单的方法,并且规则的工作将很容易为您