一、Spring入门
1、spring原理
spring的最大作用ioc/di,将类与类的依赖关系写在配置文件中(applicationContext.xml),程序在运行时根据配置文件动态加载依赖的类,降低的类与类之间的藕合度(低耦合,高内聚)。可以看出spring之间的交互是通过“反射”来实现的,这样就限制了spring的处理速度慢。具体应用:在bean标记中通过class属性说明具体类名、通过property标签说明该类的属性名、通过constructor-args说明构造子的参数。其一切都是反射,当通过applicationContext.getBean(“id名称”)得到一个类实例时,就是以bean标签的类名、属性名、构造子的参数为准,通过反射实例对象,唤起对象的set方法设置属性值、通过构造子的newInstance实例化得到对象。
2、Spring初体验
这一节我用一个具体的例子Greeting,来说明使用Spring开发的一般流程和方法,以及Spring配置文件的写法。
先建立一个Speaker类:
public class Speaker{
public void sayHello(){
System.out.println("hello,laixiao");
}
}
在建立一个Greeting类:
public class Greeting{
private Speaker speaker;
public void setSpeaker(Speaker speaker){
this.speaker = speaker;
}
public void greet(){
speaker.sayHello();
}
}
然后要创建一个Spring的配置文件把这两个类关联起来。(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"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="speaker" class="Speaker"></bean>
<bean id="greeting" class="Greeting"></bean>
要用Spring Framework必须把Spring的包加入到Classpath中。例如在自己的.classpath中有这样一段代码:
<classpathentry kind="lib" path="rc-api.jar"/。
新建一个主函数来获取这些方法;
public static void main(String[] args)
{
ApplicationContext context =
New ClassPathXmlApplicationContext("applicationContext.xml");
//Greeting为bean中id的值
Greeting greeting = (Greeting)context.getBean("Greeting");
greeting.greet();
}
上面的这就是一个简单的流程。
二、Hibernate入门
使用Hibernate框架,不用写JDBC代码,仅仅是调用一个save方法,就可以将对象保存到关系数据库中,仅仅是调用一个get方法,就可以从数据库中加载出一个对象。
Hibernate使用时的配置流程和注意事项:
1、使用Hibernate的基本流程是:配置Configuration对象、产生SessionFactory、创建session对象、启动事务、完成CRUD操作、提交事务、关闭session。
2、使用Hibernate时,先要配置hibernate.cfg.xml文件,hibernate.cfg.xml文件中需要等级每一个hbm.xml文件。
3、在应用Hibernate时,重点要了解session的缓存原理,延缓,延迟加载和hql查询。
具体安装配置:http://blog.csdn.net/doodoofish/article/details/43207
安装中常见错误:http://blog.csdn.net/mike_caoyong/article/details/6400604