ApplicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context "
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true">
<context:annotation-config />
<context:component-scan base-package="com.xued.techevaluate.ioc,com.xued.techevaluate" />
</beans>
除了要注入一些外部资源,基本上不再需要配置<bean/>项。
两个bean的代码,实现同一个接口
@Component(value="Bloomberg")
public class BloombergDataService implements MarketDataService{
@PostConstruct
private void init(){
System.out.println ("Bloomberg service initiallized");
}
public String getStockData(String stockCode) {
StringBuilder sb = new StringBuilder();
sb.append("/*************************************************************\n" +
"* Bloomberg market Data Provider *\n" +
"*************************************************************/\n");
sb.append("StockCode Company Price Amount Time ");
sb.append("\n");
sb.append(stockCode + " 长江实业 136.60 200000 "+ new Date());
return sb.toString();
}
}
@Component(value="Reuters")
public class ReutersDataService implements MarketDataService{
@PostConstruct
private void init(){
System.out.println("Reuters service initiallized");
}
public String getStockData(String stockCode) {
StringBuilder sb = new StringBuilder();
sb.append("/*************************************************************\n" +
"* Reuters market Data Provider *\n" +
"*************************************************************/\n");
sb.append("StockCode Company Price Amount Time ");
sb.append ("\n");
sb.append(stockCode + " 长江实业 136.60 200000 "+ new Date());
return sb.toString();
}
}
注入的代码:
@Component(value="dataMiner")
public class DataMiner {
@Resource(name="Reuters")
private MarketDataService dataService;
public String queryByCode(String stockCode){
return dataService.getStockData(stockCode);
}
}
采用传统方式取得bean引用:
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
instance = (DataMiner)ctx.getBean("dataMiner");
没有评论:
发表评论