决定把在javaeye上最后一点积分用光,大家投隐藏吧,投新手吧,不过我还是要说,盲从--中国程序员的悲哀。
尝试是好事,盲从就不好了。
现在我开始尝试使用一种简单的方式来构建对象,获取对象。可称之为ContextHolder模式。
- /**
- * 2007-6-5 下午02:27:03
- */
- /**
- * @author <a href="mailto:guileen@gmail.cn">桂健雄</a>
- * @since 2007-6-5
- */
- public abstract class ContextHolder {
- static{
- //init the context ,sessionFactory
- AnnotationConfiguration cfg = new AnnotationConfiguration();
- Properties prop = new Properties();
- InputStream is = null;
- try{
- is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
- prop.load(is);
- } catch (IOException e) {
- Logger.getLogger(Properties.class).error("jdbc.properties 读取失败");
- }finally{
- if(is != null){
- try {
- is.close();
- } catch (IOException e) {
- }
- }
- }
- cfg.addProperties(prop);
- initAnnotatedClasses(cfg);
- buildDaos();
- sessionFactory = cfg.buildSessionFactory();
- SessionHolder.setSessionFactory(getSessionFactory());
- }
- private static SessionFactory sessionFactory;
- private static MyDao1 dao1;
- private static MyDao2 dao2;
- /**
- * @param cfg
- */
- private static void initAnnotatedClasses(AnnotationConfiguration cfg) {
- cfg.addAnnotatedClass(MyEntity1.class);
- cfg.addAnnotatedClass(MyEntity2.class);
- cfg.addAnnotatedClass(MyEntity3.class);
- }
- private static void buildDaos(){
- dao1 = new MyDao1Impl();
- dao2 = new MyDao2Impl();
- }
- public static SessionFactory getSessionFactory(){
- return sessionFactory;
- }
- public static MyDao1 getMyDao1(){
- return dao1;
- }
- }
IOC的目标是,建立统一的对象装配器,对象提取器。但是,使用xml的配置实在是没有必要,取对象出来还要用getBean方法,要填对象名,要作类型转换,对了,还要先设法获取ApplicationContext对象。真是无聊之极。
当然,想要使用Spring中的Bean,也不一定非要获取ApplicationContext,可以把调用者也配置到Context中,定义好set方法,在配置文件中,把调用者的property ref 到 想用到bean上。
不过,如此一来,就更加是画蛇添足了。
aop和事务管理,何必一定完全交给IoC框架呢,自己编码啊。使用框架,以为自己发现了捷径,走过去,就发现,这条小路走的不那么爽,布满荆棘。
而使用这种ContextHolder模式,一切是多么的简单明了,直接static的方法调用,ContextHolder.getMyDao1(),就ok了,而且少了一个2M的spring.jar,看着舒服,少了xml,看着舒服,少了一些无聊的getters and setters,舒服。