1

I want to declare and inject a bean through annotations. It was previously done through XML, but I need to apply on a Spring Boot project.

Here is the source 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>

The bean was later used like this

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

The only way I found is through direct instantiation

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

What would be the proper way to do this?

jpboudreault
  • 977
  • 2
  • 9
  • 17
  • You can initialize `BaseProtectedResourceDetails` in your configuration java class and then initialize bean for `OAuthRestTemplate` and pass the initialized bean of `BaseProtectedResourceDetails` in constructor. – Naman Gala Feb 19 '15 at 04:50

2 Answers2

1

I am not sure you are searching for this explanation. But if I understand you question then following information may help you.

For Sample configuration class you can see this example.

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

And for registering configuration class, you can see this SO answer.

See this for @Service, @Component, @Repository, @Controller, @Autowired related example.

Community
  • 1
  • 1
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
1

you can use @Bean annotation in your main class for example:

@SpringBootApplication
public class Application{

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

   return new OAuthRestTemplate(resourceDetails);
 }
}

and after use @Autowired to inject the object

@Autowired
private OAuthRestTemplate oAuthRestTemplate;
tcharaf
  • 630
  • 1
  • 5
  • 11
  • What if the resourceDetails needs configuration defined in a property file (like a secret key), having a field annotated with @Value could be work or would it be empty when the bean is created? – jpboudreault Feb 19 '15 at 15:10
  • 1
    you can try to use Environment object like this : @Resource Environment env; and get property like : final String myPropertyValue = environment.getProperty("myProperty"); – tcharaf Feb 19 '15 at 15:35