vendredi 27 février 2015

what is the difference between using or not Spring Beans?

Probably i'll get a lot of downvotes, but it's so confusing for me all this fact of whether use beans or not. Lets suppose this example



interface ICurrency {
String getSymbol();
}


public class CurrencyProcessor {

private ICurrency currency ;

public CurrencyProcessor(ICurrency currency) {
this.currency = currency;
}

public void doOperation(){
String symbol = currency.getSymbol();
System.out.println("Doing process with " + symbol + " currency");
// Some process...
}

}


So, to inject the ICurrency impl injection i think that i can do it by two ways:




Way 1: Without Spring beans



public class CurrencyOperator {

private ICurrency currency ;
private CurrencyProcessor processor;

public void operateDefault(){
currency = new USDollarCurrency();
processor = new CurrencyProcessor(currency)
this.processor.doOperation();
}

}


Where USDollarCurrency is an ICurrency interface implementation




Way 2: Using Spring beans



@ContextConfiguration(classes = CurrencyConfig.class)
public class CurrencyOperator {

@Autowired private ICurrency currency ;
@Autowired private CurrencyProcessor processor;

public void operateDefault(){
this.processor.doOperation();
}

}

@Configuration
public class CurrencyConfig {

@Bean
public CurrencyProcessor currencyProcessor() {
return new CurrencyProcessor(currency());
}

@Bean
public ICurrency currency() {
return new USDollarCurrency();
}




I really don't understand what would be the benefits of using Spring's beans. I read some things but what i most found was about the benefits of using DI, and as i understand, both ways are injecting the dependency that CurrencyProcessor require, what is changing is the way that i am creating and using objets, am i wrong? So in concrete, my questions are: 1. What are the benefits of using Beans at this case? 2. Why should i use Spring instead of doing it manually like first way? 3. Talking about performance, which of this cases is better?


Aucun commentaire:

Enregistrer un commentaire