可能我会得到很多反对票,但是对于我来说是否使用 bean 的所有事实都让我感到困惑。让我们假设这个例子
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...
}
}
因此,要注入 ICurrency impl 注入,我认为可以通过两种方式来实现:
方式一:不使用 Spring beans
public class CurrencyOperator {
private ICurrency currency ;
private CurrencyProcessor processor;
public void operateDefault(){
currency = new USDollarCurrency();
processor = new CurrencyProcessor(currency)
this.processor.doOperation();
}
}
其中 USDollarCurrency 是 ICurrency 接口实现
方式2:使用Spring bean
@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();
}
我实在不明白使用Spring的bean有什么好处。我读了一些东西,但我最发现的是使用 DI 的好处,据我了解,两种方式都注入了CurrencyProcessor 所需的依赖项,正在改变的是我创建和使用对象的方式,我错了吗?具体来说,我的问题是:
1. 在这种情况下使用Bean有什么好处?
2.为什么我应该使用Spring而不是像第一种方式那样手动执行?
3. 说到性能,这两种情况哪个更好?
假设您有 2 个 DAO 类,第一个用于 Oracle,第二个用于 MySQL,并且两个类都实现 DAO 接口。您可以在 Spring 配置文件中将实现定义为 bean。在业务类中你有一个 DAO 类型的属性,而在 spring 配置文件中你选择真实类型 Oracle 或 MySQL 来注入或使用 spring 注解@Autowired
这减少了耦合,并且很容易从 Oracle 迁移到 MySQL。
@Service
public class Business {
@Autowired
private Dao daoImpl;
//Business methods that invoks Dao methods
}
在 Spring 配置文件(XML 文件)中,您使用以下内容:
<bean id="daoImpl" class="app.com.MySQLDaoImpl OR app.com.OracleDaoImpl"/>
只需更改 bean 的类属性,您就可以更改整个实现,而无需更改业务类!
祝你好运。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)