简体   繁体   中英

How do i convert the following xml based spring bean to java annotation based beans?

 <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>

I want to convert this to java annotation based bean (@Bean).

  1. create a method in configuration class
  2. Construct mentioned object and return.
  3. Annotate the method with @Bean

@Bean
public com.ce.indiabringsService getindiabringsServiceBean(){
    return new com.ce.indiabringsService(consumerObj,functionObj);
}

You need to create a class with org.springframework.context.annotation @Configuration annotation.

Then use @Bean annotation on a method and return appropriate bean object.

@Bean
public com.ce.indiabringsService getMessageService(){
    return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
}

Hope this helps you out.

One more option

   @Bean
public com.ce.indiabringsService getIndiabringsService(com.ce.indiabrings.consumer  
 consumerBean,com.ce.indiabrings.value.function functionBean){
 indiabringsService indiabringsServiceBean =new indiabringsService();
 indiabringsServiceBean.setConsumer(consumerBean);
 indiabringsServiceBean.setFunction(functionBean);
 return indiabringsServiceBean;
}

you can inject indiabringsService by using @Autowired .

for creating indiabringsService bean, Internally spring will automatically inject consumer and function beans while creating indiabringsService bean.

@Configuration
public class MyConfigurationClass {
    @Bean
    public com.ce.indiabringsService getIndiaBringsService() {
        return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
    }
}

And then you can autowire it as follows:

@Autowired
private com.ce.indiabringsService myIndiaBringsService;

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