简体   繁体   中英

Replacing Spring bean injection via XML with annotation injection

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM