1.原来的项目
2.优化的思想:
项目目录:
1.Dao
2.Service
import cn.oracle.books.dao.IBookDao;
import cn.oracle.domain.Book;
publicclassBookService implements IBookService {
//private BookDaodao = new BookDao();
private IBookDaodao ;
publicvoid setDao(IBookDao dao) {
this.dao = dao;
}
public List<Book>query(String typeid) {
returndao.query(typeid);
}
public Book load(Stringbookid) {
returndao.load(bookid);
}
}
3.Servlet
4. BeanFactory
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import cn.oracle.books.service.IBookService;
import cn.oracle.domain.Book;
publicclassBeanFactory {
//声明一个map<id,object>
privatestaticMap<String,Object> map =newHashMap<String,Object>();
static{
try {
//获取文件的目录
Stringpath = BeanFactory.class.getClassLoader().getResource("beans.xml").getPath();
System.err.println("path is:"+path);
//解析这个xml文件
Filefile = newFile(path);
if(!file.exists()){
thrownew RuntimeException("文件不存在");
}
SAXReadersax = newSAXReader();
Documentdom = sax.read(file);
List<Element>list = dom.selectNodes("//bean");
//把独到的id放到map并把这个类实例化
for (Element el : list) {
Stringid = el.attributeValue("id");
Stringcls = el.attributeValue("class");
Objectobj = Class.forName(cls).newInstance();
map.put(id, obj);
//再判断是否存在property这样的子元素
List<Element>props =el.elements("property");
if(props!=null &&props.size()>0){
for (Element p : props) {
Stringname = p.attributeValue("name");
Stringref = p.attributeValue("ref");//ref是bookDao(BookDao的id)
//获取放到map中的对象
Objectval = map.get(ref);
if(val==null){
load(dom,ref);
val= map.get(ref);
}
//干的是:setDao(IBookDaodao)
BeanUtils.setProperty(obj,name, val);//obj是BookService,name是dao,val是BookDao
}
}
}
}catch(Exception e) {
thrownew RuntimeException(e);
}
}
publicstaticObject getBean(String id){
returnmap.get(id);
}
publicstaticvoidload(Document dom,String beanid)throws Exception{
Elementel = (Element) dom.selectSingleNode("//bean[@id='"+beanid+"']");
Stringid = el.attributeValue("id");
Stringcls = el.attributeValue("class");
Objectobj = Class.forName(cls).newInstance();
map.put(id, obj);
}
}
5.beans.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beans>
<!-- 声明BooksDao的实例 -->
<beanid="bookDao"class="cn.oracle.books.dao.BookDao">
</bean>
<beanid="bookService"class="cn.oracle.books.service.BookService">
<propertyname="dao"ref="bookDao"/>
</bean>
</beans>