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?

1
  • You can initialize BaseProtectedResourceDetails in your configuration java class and then initialize bean for OAuthRestTemplate and pass the initialized bean of BaseProtectedResourceDetails in constructor. Commented Feb 19, 2015 at 4:50

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

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?
you can try to use Environment object like this : @Resource Environment env; and get property like : final String myPropertyValue = environment.getProperty("myProperty");
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.