JavaEE-Spring
2015年10月19日
面向接口编程和组件解耦:IoC。
工作流:AOP。
可维护性更强,更新时只需更新Bean和配置文件,逻辑和接口无需更改。
Spring是于2003 年兴起的一个轻量级的Java 开源框架,面向接口编程和面向切面编程,减少模块间的耦合,提高可维护性和复用性。
参考:http://baike.baidu.com/subview/23023/11192342.htm
参考:http://blog.csdn.net/seven_3306/article/details/7881336
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Sum2.java
package lee;
public class Sum2implements ISum {
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b+1;
}
}
id指xml的id(必须唯一,命名有限定),name是id的更加可读性名称。
参考:
http://stackoverflow.com/questions/874505/difference-between-using-bean-id-and-name-in-spring-configuration-file
//bean.java
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum" name="sum1"class="lee.Sum"></bean>
</beans>
//Test.java
package lee;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Test{
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
}
}
结果:
可以将bean.xml修改为由Sum2实现,其它都不改,结果也相应改变。
参见:构造接口和POJO
参见:配置映射文件:id指定bean的id,class指定实现此bean的POJO。
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>lee.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/h</url-pattern>
</servlet-mapping>
</web-app>
//Hello.java(Servlet)
package lee;
importjava.io.IOException;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//writeto server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
((ClassPathXmlApplicationContext)ctx).close();
}
}
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("lee.Sum.Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
System.out.println("lee.Sum.sum(a,b)");
return a+b;
}
public void init(){
System.out.println("lee.Sum.init().");
}
public void destroy(){
System.out.println("lee.Sum.destroy().");
}
}
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>lee.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/h</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
//applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person"class="lee.Person">
</bean>
<bean id="sum"name="sum1" class="lee.Sum" init-method="init"
destroy-method="destroy">
</bean>
</beans>
//Hello.java(Servlet)
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
}
}
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("lee.Sum.Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
System.out.println("lee.Sum.sum(a,b)");
return a+b;
}
public void init(){
System.out.println("lee.Sum.init().");
}
public void destroy(){
System.out.println("lee.Sum.destroy().");
}
}
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果有多个xml,则需要指定context-param参数contextConfigLoaction。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/bean.xml</param-value>
</context-param>
目标:根据配置文件,获取bean的信息,并能够实例化bean。
流程:创建配置文件,加载配置文件,实例化。
原理:使用反射和工厂模式实例化类。
方法:
能够实例化bean,称之为容器。最基本的是BeanFactory,一般使用其扩展子类ApplicationContext。
ApplicactionContext是BeanFactory的子类,提供Spring IoC所需的功能。有两个子类,FileSystemXmlApplicationContext(加载文件系统的配置文件)和ClassPathXmlApplicationContext(加载类路径中的配置文件)。
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
实例化:getBean()。
获取信息:getType(),containBean()。
<?xmlversion="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum" name="sum1"class="lee.Sum2"></bean>
<bean id="calc" name="calc"class="lee.Calc">
<!-- <property name="sum"ref="sum"></property> -->
<constructor-argname="sum" ref="sum"></constructor-arg>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
</beans>
注意:bean的实现类必须具有无参数构造函数和getter/setter(如果有属性)。
id是唯一标识,作为xml的id存在,name是bean的更加人性名的命名(可选,如果只有name,没有id,则默认将name作为id)。
<bean id="sum"name="sum1" class="lee.Sum2"></bean>
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc"name="calc" class="lee.Calc">
<property name="sum"ref="sum"></property>
<propertyname="a" value="10"></property>
<propertyname="b" value="2"></property>
</bean>
</beans>
//Calc.java
package lee;
public class Calcimplements ICalc {
public Calc() {}
public Calc(ISum sum) {
super();
this.sum = sum;
}
private int a;
private int b;
private ISumsum;
public ISum getSum() {
return sum;
}
public void setSum(ISum sum) {
this.sum = sum;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int calc() {
// TODO Auto-generated method stub
return sum.sum(a, b);
}
}
//ICalc.java
package lee;
public interfaceICalc {
public int calc();
}
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Hello.java
package lee;
importjava.io.IOException;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
//spring ioc
ICalc calc=ctx.getBean("calc",ICalc.class);
System.out.print("calc()="+calc.calc());
pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");
}
}
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc"name="calc" class="lee.Calc">
<constructor-argname="sum" ref="sum"></constructor-arg>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
</beans>
//Calc.xml
package lee;
public class Calcimplements ICalc {
public Calc() {}
public Calc(ISum sum) {
super();
this.sum = sum;
}
private int a;
private int b;
private ISum sum;
public ISum getSum() {
return sum;
}
public void setSum(ISum sum) {
this.sum = sum;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int calc() {
// TODO Auto-generated method stub
return sum.sum(a, b);
}
}
//ICalc.java
package lee;
public interfaceICalc {
public int calc();
}
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Hello.java
package lee;
importjava.io.IOException;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//writeto server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
//spring ioc
ICalc calc=ctx.getBean("calc",ICalc.class);
System.out.print("calc()="+calc.calc());
pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");
}
}
使用bean的scope属性指定。
<beanid="calc" name="calc" class="lee.Calc"scope="prototype">
指定根据何种规则自动生成bean与属性配对。
<bean id="calc"name="calc" class="lee.Calc" autowire="byName">
示例:Calc依赖Sum,则先初始化Sum,实例化Calc,然后设值。
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc" name="calc"class="lee.Calc">
<propertyname="sum" ref="sum"></property>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
</beans>
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Calc.java
package lee;
public class Calcimplements ICalc {
public Calc() {
System.out.println("Calc().");
}
public Calc(ISum sum) {
super();
this.sum = sum;
}
private int a;
private int b;
private ISum sum;
public ISum getSum() {
return sum;
}
public void setSum(ISum sum) {
this.sum = sum;
System.out.println("setSum().");
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int calc() {
// TODO Auto-generated method stub
return sum.sum(a, b);
}
}
默认实例化:Spring默认调用bean的构造函数生成实例。
工厂静态方法:指定一个工厂类和静态方法创建实例。
<bean id="calc" name="calc"class="lee.Person" factory-method="createCalc">
<constructor-argvalue="sum2"></constructor-arg>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
自定义工厂bean:定义一个工厂bean,指定工厂bean和创建方法。
<bean id="person"class="lee.Person"></bean>
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc" name="calc"factory-bean="person" factory-method="createCalc">
<constructor-argvalue="sum2"></constructor-arg>
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc" name="calc"class="lee.Person" factory-method="createCalc">
<constructor-argvalue="sum2"></constructor-arg>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
</beans>
//Person.java工厂类
package lee;
public classPerson {
public static ICalc createCalc(String msg){
System.out.println("createCalc="+msg);
if (msg.equals("sum2")) {
System.out.println("createCalc=createsum2");
return new Calc(new Sum2());
} else {
System.out.println("createCalc=createsum");
return new Calc(new Sum());
}
}
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Calc.java
package lee;
public class Calcimplements ICalc {
public Calc() {
System.out.println("Calc().");
}
public Calc(ISum sum) {
super();
this.sum = sum;
}
private int a;
private int b;
private ISum sum;
public ISum getSum() {
return sum;
}
public void setSum(ISum sum) {
this.sum = sum;
System.out.println("setSum().");
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int calc() {
// TODO Auto-generated method stub
return sum.sum(a, b);
}
}
//Hello.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
//spring ioc
ICalc calc=ctx.getBean("calc",ICalc.class);
System.out.print("calc()="+calc.calc());
pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");
}
}
//Sum2.java
package lee;
public class Sum2implements ISum {
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b+1;
}
}
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person"class="lee.Person"></bean>
<bean id="sum"name="sum1" class="lee.Sum"></bean>
<bean id="calc" name="calc"factory-bean="person" factory-method="createCalc">
<constructor-argvalue="sum2"></constructor-arg>
<property name="a"value="10"></property>
<property name="b"value="2"></property>
</bean>
</beans>
//Person.java工厂类
package lee;
public classPerson {
public ICalc createCalc(String msg) {
System.out.println("createCalc="+msg);
if (msg.equals("sum2")) {
System.out.println("createCalc=createsum2");
return new Calc(new Sum2());
} else {
System.out.println("createCalc=createsum");
return new Calc(new Sum());
}
}
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
}
//Calc.java
package lee;
public class Calcimplements ICalc {
public Calc() {
System.out.println("Calc().");
}
public Calc(ISum sum) {
super();
this.sum = sum;
}
private int a;
private int b;
private ISum sum;
public ISum getSum() {
return sum;
}
public void setSum(ISum sum) {
this.sum = sum;
System.out.println("setSum().");
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public int calc() {
// TODO Auto-generated method stub
return sum.sum(a, b);
}
}
//Hello.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
//spring ioc
ICalc calc=ctx.getBean("calc",ICalc.class);
System.out.print("calc()="+calc.calc());
pw.println("<h1>Springcalc()=="+calc.calc()+"</h1>");
}
}
【BeanFactory后处理器】:如果有则在容器属性配置完成后执行postProcessBeanFactory()。
创建实例:new。
注入:执行属性注入。
【Bean后处理器】:如果有则在初始化前执行postProcessBeforeInitialization(),初始化完成后执行postProcessAfterInitialization()。
初始化方法:注入完成后执行init-method。
执行各自操作。
销毁方法:执行destroy-method。
方法:配置Bean的init-method为方法名,destroy-method为方法名。
参考:http://outofmemory.cn/java/spring/spring-bean-init-method-and-destroy-method
<bean id="sum"name="sum1" class="lee.Sum" init-method="init" destroy-method="destroy">
目标:在spring容器初始化后执行动作。
原理:回调函数。
流程:创建BeanFactoryPostProcessor的实现类,配置Bean,Spring自动检测并执行。
<beanclass="lee.FactoryBeanProcess"></bean>
目标:在Bean初始化后执行动作。
原理:回调函数。
流程:创建BeanPostProcessor的实现类,配置Bean,Spring自动检测并执行。
<beanclass="lee.FactoryBeanProcess"></bean>
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sum" name="sum1"class="lee.Sum" init-method="init"
destroy-method="destroy">
</bean>
<bean class="lee.PostProcess"></bean>
<beanclass="lee.FactoryBeanProcess"></bean>
</beans>
//Hello.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
((ClassPathXmlApplicationContext)ctx).close();
}
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
public void init(){
System.out.println("init().");
}
public void destroy(){
System.out.println("destroy().");
}
}
//PostProcess.java
package lee;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.config.BeanPostProcessor;
public classPostProcess implements BeanPostProcessor {
@Override
public ObjectpostProcessAfterInitialization(Object arg0, String arg1) throws BeansException{
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization:"+arg0+","+arg1);
return arg0;
}
@Override
public ObjectpostProcessBeforeInitialization(Object arg0, String arg1) throws BeansException{
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization:"+arg0+","+arg1);
return arg0;
}
}
//FactoryPostProcess.java
package lee;
importorg.springframework.beans.BeansException;
importorg.springframework.beans.factory.config.BeanFactoryPostProcessor;
importorg.springframework.beans.factory.config.ConfigurableListableBeanFactory;
public classFactoryBeanProcess implements BeanFactoryPostProcessor {
@Override
public voidpostProcessBeanFactory(ConfigurableListableBeanFactory arg0) throwsBeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeanFactory:"+arg0);
}
}
目标:实现访问各种资源,统一处理。
原理:各种不同的资源实现Resource接口,统一操作方法。
方法:
UrlResource,ClassPathResource,FileSystemResource,ServletContextResource,InputStreamResource,ByteArrayResource。
打开文件:getFile(),getURL(),getInputStream()。
判断状态:isOpen()。
判断是否存在:exists()。
描述信息:getDescription()。
示例:
参考:http://blog.csdn.net/z69183787/article/details/8110948
下载aspectj.jar,解压后,将lib中的jar复制到工程的lib文件夹中,将jar加入到classpath。
下载aopalliance.jar,复制到工程的lib文件夹中,将jar加入到classpath。
基本的Bean,执行常规操作。
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("lee.Sum.Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
System.out.println("lee.Sum.sum(a,b)");
return a+b;
}
public void init(){
System.out.println("lee.Sum.init().");
}
public void destroy(){
System.out.println("lee.Sum.destroy().");
}
}
用于执行各个切入点的操作。
//Person.java
package lee;
importorg.aspectj.lang.JoinPoint;
importorg.aspectj.lang.ProceedingJoinPoint;
public classPerson {
public Person() {
super();
// TODO Auto-generated constructorstub
System.out.println("Person().");
}
public void beforeAop(JoinPoint jp){
System.out.println("beforeaop..."+jp.getTarget());
}
public void afterAop(JoinPoint jp){
System.out.println("afteraop..."+jp.getTarget());
}
}
配置切入点和切入操作。
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person"class="lee.Person"></bean>
<bean id="sum"name="sum1" class="lee.Sum" init-method="init"
destroy-method="destroy">
</bean>
<aop:config>
<aop:aspectref="person" id="afterAdviceAspect">
<aop:pointcutid="sumAop" expression="execution(* *.*(..))" />
<aop:beforemethod="beforeAop" pointcut-ref="sumAop" />
<aop:aftermethod="afterAop" pointcut-ref="sumAop" />
</aop:aspect>
</aop:config>
</beans>
切面aspect:一个具体的工作流单位。其中包括切入点,各个切入点对应的处理。
切入点pointcut:工作流的切入位置。具体指一个函数调用时机,可以设置多个,如servlet的url。可以在此切入点设置各种处理。
处理Advice:对切入点进行各种操作。可以在切入点之前、之后等多种时机设置处理。
连接点JoinPoint:工作流的具体切入的函数。
参数arg-names:连接点的实参,可以在这里指定名称。
参考:http://blog.csdn.net/zuyi532/article/details/7992323
http://blog.csdn.net/awangz/article/details/7750081
http://blog.csdn.net/wangpeng047/article/details/8556800
proceed()将执行切入点调用。
public ObjectaroundAop(ProceedingJoinPoint jp) throws Throwable{
System.out.println("aroundaop:before..."+jp.getTarget());
Object obj=jp.proceed();
System.out.println("aroundaop:after..."+jp.getTarget());
return obj;
}
<aop:after-returningmethod="afterRet" pointcut-ref="sumAop"
returning="ret" />
public void afterRet(JoinPoint jp,Object ret){
System.out.println("afterRetaop..."+jp.getTarget()+"="+ret);
}
<aop:after-throwingmethod="afterThrowing"
pointcut-ref="sumAop"throwing="ex"/>
public void afterThrowing(JoinPoint jp,Throwable ex) throwsThrowable{
System.out.println("throwingaop..."+jp.getTarget()+"="+ex.getMessage());
}
//bean.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person"class="lee.Person">
</bean>
<bean id="sum"name="sum1" class="lee.Sum" init-method="init"
destroy-method="destroy">
</bean>
<aop:config>
<aop:aspect ref="person"id="afterAdviceAspect">
<aop:pointcutid="sumAop" expression="execution(* *.*(..))" />
<aop:beforemethod="beforeAop"
pointcut="execution(intlee.Sum.sum(..)); args(int,int)" />
<aop:aftermethod="afterAop" pointcut-ref="sumAop" />
<aop:aroundmethod="aroundAop" pointcut-ref="sumAop" />
<aop:after-returningmethod="afterRet" pointcut-ref="sumAop"
returning="ret"/>
<aop:after-throwingmethod="afterThrowing"
pointcut-ref="sumAop"throwing="ex" />
</aop:aspect>
</aop:config>
</beans>
//Person.java
package lee;
importorg.aspectj.lang.JoinPoint;
importorg.aspectj.lang.ProceedingJoinPoint;
public classPerson {
public Person() {
super();
// TODO Auto-generated constructorstub
System.out.println("Person().");
}
public ICalc createCalc(String msg) {
System.out.println("createCalc="+msg);
if (msg.equals("sum2")) {
System.out.println("createCalc=createsum2");
return new Calc(new Sum2());
} else {
System.out.println("createCalc=createsum");
return new Calc(new Sum());
}
}
public void beforeAop(JoinPoint jp){
System.out.println("beforeaop..."+jp.getTarget()+"="+jp.getArgs().length+",0="+jp.getArgs()[0]);
}
public void afterAop(JoinPoint jp){
System.out.println("after aop..."+jp.getTarget());
}
public ObjectaroundAop(ProceedingJoinPoint jp) throws Throwable{
System.out.println("aroundaop:before..."+jp.getTarget());
Object obj=jp.proceed();
System.out.println("aroundaop:after..."+jp.getTarget());
return obj;
}
public void afterThrowing(JoinPointjp,Throwable ex) throws Throwable{
System.out.println("throwingaop..."+jp.getTarget()+"="+ex.getMessage());
}
public void afterRet(JoinPoint jp,Objectret){
System.out.println("afterRetaop..."+jp.getTarget()+"="+ret);
}
}
//ISum.java
package lee;
public interfaceISum {
public int sum(int a,int b);
}
//Sum.java
package lee;
public class Sumimplements ISum {
public Sum(){
System.out.println("lee.Sum.Sum().");
}
@Override
public int sum(int a, int b) {
// TODO Auto-generated method stub
System.out.println("lee.Sum.sum(a,b)");
return a+b;
}
public void init(){
System.out.println("lee.Sum.init().");
}
public void destroy(){
System.out.println("lee.Sum.destroy().");
}
}
//Hello.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Helloextends HttpServlet {
protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring
ApplicationContext ctx=newClassPathXmlApplicationContext("bean.xml");
ISumsum=ctx.getBean("sum",ISum.class);
System.out.print("1+2="+sum.sum(1,2));
pw.println("<h1>Spring="+sum.sum(1,2)+"</h1>");
((ClassPathXmlApplicationContext)ctx).close();
}
}
参见:Java Web:Http服务器托管的Spring容器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果有多个xml,则需要指定context-param参数contextConfigLoaction。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/bean.xml</param-value>
</context-param>
注意:scope是prototype,每次请求才生成实例。
<bean id="beanAction" class="lee.BeanAction" scope="prototype">
</bean>
//BeanAction.java.xml
package lee;
importcom.opensymphony.xwork2.Action;
public classBeanAction implements Action {
// private ISum sm;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("lee.BeanAction.execute()...");
return ERROR;
}
//struts.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPEstruts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee"extends="struts-default">
<action name="h"class="beanAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
//struts.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPEstruts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee"extends="struts-default">
<action name="h"class="beanAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanAction" class="lee.BeanAction" scope="prototype">
</bean>
</beans>
//BeanAction.java
package lee;
importcom.opensymphony.xwork2.Action;
public class BeanAction implements Action {
// private ISum sm;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("lee.BeanAction.execute()...");
return ERROR;
}
Spring默认使用name自动装配,如果property的name与bean的id相同,则自动进行装配,如果不同,则需要使用ref指定。
<bean id="beanAction"class="lee.BeanAction" scope="prototype">
<property name="sm" ref="sum"/>
</bean>
参见:安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的WEB-INF/lib目录下。将WEB-INF/lib下的jar加入buildpath。
参见:JavaEE-ORM映射器Hibernate.docx中Hibernate库安装部分。
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>beanAction</servlet-name>
<servlet-class>lee.BeanAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>beanAction</servlet-name>
<url-pattern>/h</url-pattern>
</servlet-mapping>
<!-- spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
//applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanAction" class="lee.BeanAction"scope="prototype">
<propertyname="sf" ref="sessionFactory"></property>
</bean>
<!-- hibernate -->
<beanid="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/hib4</value>
</property>
<property name="username">
<value>root</value>
</property>
<propertyname="password">
<value>sf</value>
</property>
</bean>
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource" ref="dataSource">
</property>
<propertyname="mappingResources">
<list>
<!--
!这里填写hibernate的映射文件路径
-->
<value>lee/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<!--
配置Hibernate的方言
-->
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
<!--
输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false
-->
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
//employee.java
package lee;
public classEmployee {
private int id;
private String empName;
private String empAddress;
private String empMobileNos;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(StringempAddress) {
this.empAddress = empAddress;
}
public String getEmpMobileNos() {
return empMobileNos;
}
public void setEmpMobileNos(StringempMobileNos) {
this.empMobileNos = empMobileNos;
}
}
//Employee.hbm.xml
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- GeneratedOct 29, 2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="lee.Employee"table="employee">
<id name="id"type="int">
<column name="ID"/>
<generatorclass="assigned" />
</id>
<property name="empName"type="java.lang.String">
<columnname="EMP_NAME" />
</property>
<propertyname="empAddress" type="java.lang.String">
<columnname="EMP_ADDRESS" />
</property>
<propertyname="empMobileNos" type="java.lang.String">
<columnname="EMP_MOBILE_NOS" />
</property>
</class>
</hibernate-mapping>
//BeanAction.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServlet;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
public classBeanAction extends HttpServlet {
public void service(ServletRequestrequest, ServletResponse response) throws IOException{
System.out.println("Hello,Servlet!");//writeto server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);
Session session=sf.openSession();
// read
{
Employee obj = (Employee)session.load(Employee.class, 1);
System.out.println(obj.getEmpName()+ ":" + obj.getEmpMobileNos());
System.out.println("yes,read");
}
session.close();
pw.println("<h1>Spring="+sf+"</h1>");
}
}
注意:每条操作都自动执行事务。
参考:http://bbs.csdn.net/topics/370262876
//BeanAction.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServlet;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
public classBeanAction extends HttpServlet {
public void service(ServletRequestrequest, ServletResponse response) throws IOException{
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);
Session session=sf.openSession();
// read
{
Employee obj = (Employee)session.load(Employee.class, 1);
System.out.println(obj.getEmpName()+ ":" + obj.getEmpMobileNos());
System.out.println("yes,read");
}
//template
{
HibernateTemplate temp=new HibernateTemplate(sf);
Employee emp1=new Employee();
emp1.setId(18);
emp1.setEmpName("newEmp");
emp1.setEmpAddress("new addr");
emp1.setEmpMobileNos("1223378");
temp.save(emp1);//Create
Employee obj=temp.get(Employee.class, 18);// Retrieve
System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());
obj.setEmpAddress("updateaddr");
temp.update(obj);//Update
Employeeobj2=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());
temp.delete(emp1);//Delete
}
session.close();
pw.println("<h1>Spring="+sf+"</h1>");
}
}
//结果
目标:在execute中自定义执行方法,可以使用Hibernate的原生方法。
方法:实现HibernateCallback接口,调用execute()。
//MyGet.java
package lee;
importjava.sql.SQLException;
importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.springframework.orm.hibernate3.HibernateCallback;
public class MyGet implementsHibernateCallback<Employee> {
@Override
public Employee doInHibernate(Sessionsession) throws HibernateException, SQLException {
// TODO Auto-generated method stub
System.out.println("HibernateCallback:getsession.");
Employee obj = (Employee)session.load(Employee.class, 1);
System.out.println(obj.getEmpName() +":" + obj.getEmpMobileNos());
System.out.println("yes,Callback");
return obj;
}
}
//BeanAction.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServlet;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
public classBeanAction extends HttpServlet {
public void service(ServletRequestrequest, ServletResponse response) throws IOException{
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SessionFactorysf=ctx.getBean("sessionFactory",SessionFactory.class);
Session session=sf.openSession();
//template
{
HibernateTemplate temp=newHibernateTemplate(sf);
temp.execute(new MyGet());
Employee emp1=new Employee();
emp1.setId(18);
emp1.setEmpName("newEmp");
emp1.setEmpAddress("newaddr");
emp1.setEmpMobileNos("1223378");
temp.save(emp1);
Employeeobj=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());
obj.setEmpAddress("updateaddr");
temp.update(obj);
Employeeobj2=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());
temp.delete(emp1);
}
session.close();
pw.println("<h1>Spring="+sf+"</h1>");
}
}
目标:自动管理SessionFactory的读写,Session的开关,HibernateTemplate的生成。
原理:封装固定操作。
流程:配置Spring和Servlet;使用Spring配置Hibernate的SessionFactory;创建表的映射实体类和映射文件;创建HibernateDaoSupport的Bean,直接使用HibernateTemplate;在Servlet中使用HibernateDaoSupport的Bean。
配置Spring和Servlet
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>beanAction</servlet-name>
<servlet-class>lee.BeanAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>beanAction</servlet-name>
<url-pattern>/h</url-pattern>
</servlet-mapping>
<!-- spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
使用Spring配置Hibernate的SessionFactory
//applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanAction"class="lee.BeanAction" scope="prototype">
</bean>
<bean id="daoTest" class="lee.DaoTest"scope="prototype">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<!-- hibernate -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/hib4</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>sf</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource">
</property>
<propertyname="mappingResources">
<list>
<!--
!这里填写hibernate的映射文件路径
-->
<value>lee/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<!--
配置Hibernate的方言
-->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
<!--
输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false
-->
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
创建表的映射实体类和映射文件
//employee.java
package lee;
public classEmployee {
private int id;
private String empName;
private String empAddress;
private String empMobileNos;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(StringempAddress) {
this.empAddress = empAddress;
}
public String getEmpMobileNos() {
return empMobileNos;
}
public void setEmpMobileNos(StringempMobileNos) {
this.empMobileNos = empMobileNos;
}
}
//Employee.hbm.xml
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- GeneratedOct 29, 2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="lee.Employee"table="employee">
<id name="id"type="int">
<column name="ID"/>
<generatorclass="assigned" />
</id>
<property name="empName"type="java.lang.String">
<column name="EMP_NAME"/>
</property>
<propertyname="empAddress" type="java.lang.String">
<columnname="EMP_ADDRESS" />
</property>
<propertyname="empMobileNos" type="java.lang.String">
<columnname="EMP_MOBILE_NOS" />
</property>
</class>
</hibernate-mapping>
创建HibernateDaoSupport的Bean
//DaoTest.java
package lee;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class DaoTest extends HibernateDaoSupport {
public void test(){
HibernateTemplate temp=getHibernateTemplate();
System.out.println(temp);
temp.execute(new MyGet());
Employee emp1=new Employee();
emp1.setId(18);
emp1.setEmpName("new Emp");
emp1.setEmpAddress("newaddr");
emp1.setEmpMobileNos("1223378");
temp.save(emp1);
Employee obj=temp.get(Employee.class,18);
System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());
obj.setEmpAddress("updateaddr");
temp.update(obj);
Employeeobj2=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());
temp.delete(emp1);
}
}
在Servlet中使用HibernateDaoSupport的Bean
//BeanAction.java
package lee;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServlet;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
public classBeanAction extends HttpServlet {
public void service(ServletRequestrequest, ServletResponse response) throws IOException{
System.out.println("Hello,Servlet!");//write to server
//write to client
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
DaoTestdt=ctx.getBean("daoTest",DaoTest.class);
dt.test();
pw.println("<h1>Spring="+dt.getSessionFactory()+"</h1>");
}
}
方法:
设置SessionFactory:使用Bean设置,将此bean设置为sessionFactory属性。
设置Session:自动管理,每次事件开闭一次。
目标:使用声明式的事务管理程序的事务流程。
原理:AOP进行事务控制。
流程:在bean配置中设置aop的事务切点,切点使用事务tx处理。
<beanid="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"ref="sessionFactory"></property>
</bean>
<tx:adviceid="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:methodname="*" />
</tx:attributes>
</tx:advice>
<aop:config >
<aop:pointcutid="sumAop" expression="execution(* lee.DaoTest.test(..))"/>
<aop:advisor pointcut-ref="sumAop"advice-ref="txAdvice"></aop:advisor>
</aop:config>
方法:
参考:http://www.cnblogs.com/rushoooooo/archive/2011/08/28/2155960.html
事务性处理:<tx:advice>
事务管理器:需要设置sessionFactory属性。
示例:
安装Struts库:参见:JavaEE-控制器Struts2.docx安装库部分。
安装spring插件库:struts2-spring-plugin-2.3.16.jar,在Struts的lib目录下,copy到web-inf/lib下,并加入classpath。
安装Spring库:参见:安装Spring库:下载Spring,解压,将libs和depends下的库都copy到工程的lib目录下。配置BuildPath,将lib下的jar全部加入buildpath。
安装Hibernate库:参见:JavaEE-ORM映射器Hibernate.docx中Hibernate库安装部分
配置Spring监听器:在web.xml中配置。
配置Struts过滤器:在web.xml中配置过滤器,配置struts.xml。
配置Hibernate连接参数:在applicationContext.xml中配置。
//web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
//struts.xml
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee" extends="struts-default">
<actionname="h" class="beanAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//applicationContext.xml
</web-app>
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!--hibernate -->
<beanid="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/hib4</value>
</property>
<propertyname="username">
<value>root</value>
</property>
<propertyname="password">
<value>sf</value>
</property>
</bean>
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource" ref="dataSource">
</property>
<propertyname="mappingResources">
<list>
<!-- !这里填写hibernate的映射文件路径 -->
<value>lee/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<!-- 配置Hibernate的方言 -->
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
<!-- 输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false-->
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="beanAction"class="lee.BeanAction" scope="prototype">
</bean>
<bean id="daoTest"class="lee.DaoTest" scope="prototype">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
</beans>
获取Bean:一种是使用属性在配置文件中设置,另一种是使用context直接获取。
WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
DaoTestdt=ctx.getBean("daoTest",DaoTest.class);
//BeanAction.java
package lee;
import java.io.PrintWriter;
importorg.apache.struts2.ServletActionContext;
importorg.springframework.web.context.WebApplicationContext;
importorg.springframework.web.context.support.WebApplicationContextUtils;
importcom.opensymphony.xwork2.ActionSupport;
public class BeanAction extendsActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
//write to client
ServletActionContext.getResponse().setContentType("text/html");
PrintWriter pw=ServletActionContext.getResponse().getWriter();
pw.println("<h1>Hello,I amServlet.</h1>");
//spring with web
WebApplicationContextctx=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
DaoTest dt=ctx.getBean("daoTest",DaoTest.class);
dt.test();
pw.println("<h1>Spring="+dt.getSessionFactory()+"</h1>");
return null;
}
}
//Employee.java
package lee;
public class Employee {
private int id;
private String empName;
private String empAddress;
private String empMobileNos;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getEmpMobileNos() {
return empMobileNos;
}
public void setEmpMobileNos(String empMobileNos) {
this.empMobileNos = empMobileNos;
}
}
//Employee.hbm.xml
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 29,2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="lee.Employee"table="employee">
<id name="id"type="int">
<column name="ID"/>
<generatorclass="assigned" />
</id>
<property name="empName"type="java.lang.String">
<columnname="EMP_NAME" />
</property>
<propertyname="empAddress" type="java.lang.String">
<columnname="EMP_ADDRESS" />
</property>
<propertyname="empMobileNos" type="java.lang.String">
<columnname="EMP_MOBILE_NOS" />
</property>
</class>
</hibernate-mapping>
//DaoTest.java
package lee;
importorg.hibernate.SQLQuery;
import org.hibernate.Session;
importorg.hibernate.Transaction;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class DaoTest extends HibernateDaoSupport{
public void test(){
HibernateTemplate temp=getHibernateTemplate();
System.out.println(temp);
Employee emp1=new Employee();
emp1.setId(18);
emp1.setEmpName("new Emp");
emp1.setEmpAddress("new addr");
emp1.setEmpMobileNos("1223378");
temp.save(emp1);
Employee obj=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.get()="+obj.getEmpName()+ ":" + obj.getEmpAddress());
obj.setEmpAddress("update addr");
temp.update(obj);
Employee obj2=temp.get(Employee.class, 18);
System.out.println("HibernateTemplate.update()="+obj2.getEmpName()+ ":" + obj2.getEmpAddress());
temp.delete(emp1);
}
}
//Web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SpringWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
//Struts.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="lee"extends="struts-default">
<action name="login"class="lee.LoginAction">
<result name="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
<action name="h"class="beanAction">
<resultname="success">/success.jsp</result>
<resultname="error">/error.jsp</result>
</action>
</package>
</struts>
//applicationContext.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<beanid="beanAction" class="lee.BeanAction"scope="prototype">
<propertyname="sf" ref="sessionFactory"></property>
</bean>
<!--hibernate -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/hib4</value>
</property>
<property name="username">
<value>root</value>
</property>
<propertyname="password">
<value>sf</value>
</property>
</bean>
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource" ref="dataSource">
</property>
<propertyname="mappingResources">
<list>
<!--
!这里填写hibernate的映射文件路径
-->
<value>lee/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<!--
配置Hibernate的方言
-->
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
<!--
输入由Hibernate生成的SQL语句,如果在hibernate.cfg.xml中也指定的话,会生成两条语句,在产品中最好关闭,即设为false
-->
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
//Employee.hbm.xml
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 29,2015 4:52:09 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="lee.Employee" table="employee">
<id name="id"type="int">
<column name="ID"/>
<generatorclass="assigned" />
</id>
<property name="empName"type="java.lang.String">
<columnname="EMP_NAME" />
</property>
<propertyname="empAddress" type="java.lang.String">
<column name="EMP_ADDRESS"/>
</property>
<propertyname="empMobileNos" type="java.lang.String">
<columnname="EMP_MOBILE_NOS" />
</property>
</class>
</hibernate-mapping>
//BeanAction.java
package lee;
import org.hibernate.Session;
importorg.hibernate.SessionFactory;
importcom.opensymphony.xwork2.Action;
public class BeanActionimplements Action {
privateSessionFactory sf;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("lee.BeanAction.execute()...");
// hibernate
SessionFactorysf=getSf();
Session session = sf.openSession();
// read
{
Employee obj = (Employee)session.load(Employee.class, 1);
System.out.println(obj.getEmpName() + ":"+ obj.getEmpMobileNos());
System.out.println("yes,read");
}
return ERROR;
}
publicSessionFactory getSf() {
return sf;
}
public voidsetSf(SessionFactory sf) {
this.sf = sf;
}
}
//Employee.java
package lee;
public class Employee {
private int id;
private String empName;
private String empAddress;
private String empMobileNos;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getEmpMobileNos() {
return empMobileNos;
}
public void setEmpMobileNos(String empMobileNos) {
this.empMobileNos = empMobileNos;
}
}