使用注释注入通过XML替换Spring bean注入

时间:2015-02-19 04:13:36

标签: java spring spring-boot

我想通过注释声明并注入bean。它以前是通过XML完成的,但我需要在Spring Boot项目中应用。

这是源xml

<oauth:resource-details-service id="rds">
    <oauth:resource
            id="oauth1"
            key="${key}"
            secret="${secret}"
            request-token-url="${token}"
            user-authorization-url="${user-auth}"
            access-token-url="${accesstokenurl}">
    </oauth:resource>
</oauth:resource-details-service>

后来像这样使用bean

<bean class="org.springframework.security.oauth.consumer.client.OAuthRestTemplate">
    <constructor-arg ref="oauth1"/>
</bean>

我找到的唯一方法是直接实例化

BaseProtectedResourceDetails resourceDetails = new BaseProtectedResourceDetails();
resourceDetails.set...
resourceDetails.set...
OAuthRestTemplate restTemplate = new OAuthRestTemplate(resourceDetails);

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

我不确定您是否正在寻找此解释。但如果我理解你的问题,那么以下信息可能对你有帮助。

对于Sample配置类,您可以看到this示例。

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class TextEditorConfig {

   @Bean 
   public TextEditor textEditor(){
      return new TextEditor( spellChecker() );
   }

   @Bean 
   public SpellChecker spellChecker(){
      return new SpellChecker( );
   }
}

要注册配置类,您可以看到this SO answer

请参阅this了解@ Service,@ Component,@ Repository,@ Controller,@ Autowired相关示例。

答案 1 :(得分:1)

您可以在主类中使用@Bean注释,例如:

@SpringBootApplication
public class Application{

 @Bean
 public OAuthRestTemplate getAuth(){
   BaseProtectedResourceDetails resourceDetails = new BaseProtectedResourceDetails();
   resourceDetails.set...
   resourceDetails.set...

   return new OAuthRestTemplate(resourceDetails);
 }
}

并在使用@Autowired后注入对象

@Autowired
private OAuthRestTemplate oAuthRestTemplate;