ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 软件工程 >> 仿hibernate,spring框架手动写

仿hibernate,spring框架手动写(1/2)

来源:网络整理     时间:2015-12-17     关键词:线程池,Spring,Exception,Annotation

本篇文章主要介绍了"仿hibernate,spring框架手动写",主要涉及到线程池,Spring,Exception,Annotation方面的内容,对于软件工程感兴趣的同学可以参考一下: 最近学习了hibernate底层技术和Spring 的底层技术,觉得很不错,所以想分享下,要是说的不够详细,可以去下载资源自己查看下载链接技术的体现是在实际中的...

最近学习了hibernate底层技术和Spring 的底层技术,觉得很不错,所以想分享下,要是说的不够详细,可以去下载资源自己查看下载链接

技术的体现是在实际中的。现在大体介绍一下吧

首先介绍hibernate手动写:

仿HIBERNATE

hibernate是属于DAO,专门又来管理数据的,connection中还要考虑多线程的情况,同一个线程还要必须要是相同的connection对象,这就需要ThreadLocal来实现。

1,connection考虑需要多线程,需要采用多例模式来实现,

2,读取配置文件,如真的hibernate中的配置文件(自己写的只有mysqld的)

3,当需要进行事物处理的时,需要采用同一个connection对象,需要用到ThreadLocal对象进行设置

4,当connection关闭时,而不是直接关闭,只是将其还回线程池中。

具体代码呈上:


/*
 * 我们需要采用线程池避免线程冲突,多例模式----》获得时候需要上锁
 * pool中的数量是有限的,我们采用了代理模式,修改 con.close(),将连接换回来
 * 为了保证统一线程是一个用户,我们采用threadlocal本地线程技术
 */
public class hibernateFactory2 {
	private static final int NUM=3;
	private static List pool =new ArrayList();
	private static  ThreadLocal t=new ThreadLocal();//声明本地线程、
	static{
		//读取配置文件
		Properties p =new Properties();
		
			try {
				p.load(hibernateFactory2.class.getClassLoader().getResourceAsStream("jdbc.properties"));
				//读取里面的值,一直修改配置文件即可
				String driver=p.getProperty("driver");
				String url=p.getProperty("url");
				String user=p.getProperty("username");
				String password=p.getProperty("password");
				//System.out.println(driver+url+user+password);
				Class.forName(driver);
				for(int i=0;i//采用动态代理开始进行对connection接口实现代理,对con.close,实现换回去
					Object o =Proxy.newProxyInstance(hibernateFactory2.class.getClassLoader(), new Class[]{Connection.class},
							new InvocationHandler() {

								@Override
								public Object invoke(Object proxy, Method method, Object[] args)
										throws Throwable {
									if(method.getName().equals("close")){
										pool.add((Connection)(proxy));
										System.out.println("换回来了。。。");
										return null;
									}
									return method.invoke(con, args);
								}
							});
					pool.add((Connection)o);
				}
			//	System.out.println("初始化完毕"+con);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}

	public static synchronized Connection getCon() throws Exception{
		/*
		 * 把自动会到一个它所维护的那个map中去取,把以“当前线程对象”为key所对应的那个value取出来
		 */
		Connection c=t.get();
		if(c==null){
			while(pool.size()<=0){
				System.out.println("池中已经乜有连接");
				Thread.sleep(1000);
			}
			 c=pool.remove(0);//为事物处理方便了,当出现错误的时候,多表一个都不能存储。采用一个connection
			t.set(c);
		}
		return c;
	}
}

仿Spring

这一层基本上进行的是业务逻辑处理

相关图片

相关文章