众所周知Spring实现了控制反转和依赖注入
下面以一简单Web应用来说明如何通过Spring注入实现类代码如下
代码1:IDateFormat
//接口定义
package com.doit8.common.util;
public interface IDateFormat {
public String getNowDate();
}
代码2:DateFormatImpl
//实现类,该实现类作用只是取得当前日期并格式化它.
package com.doit8.common.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatImpl implements IDateFormat{
public String getNowDate() {
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(date);
return dateString;
}
}
代码3:MyBeanFactory
//Bean工产通过Spring取得注入的实现类方法,通过传入的request取得Web应用的上下文环境
package com.doit8.common.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
public class MyBeanFactory {
private static BeanFactory overrideFactory = null;
private static BeanFactory factory = null;
/**
* 获取spring实例
* @return
* @throws InstantiationException
*/
public static Object getInstance(HttpServletRequest request,String beanName) throws InstantiationException {
try {
if (overrideFactory != null) {
Object reply = overrideFactory.getBean(beanName);
return reply;
}
if (factory == null) {
factory = getBeanFactory(request);
overrideFactory = factory;
}
Object reply = factory.getBean(beanName);
return reply;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new InstantiationException(ex.toString());
}
}
/**
* 获取spring bean工厂
*
* @return
*/
private static BeanFactory getBeanFactory(HttpServletRequest request) {
ServletContext srvCtx = request.getSession().getServletContext();
if (request != null) {
return RequestContextUtils.getWebApplicationContext(request, srvCtx);
} else {
return WebApplicationContextUtils.getWebApplicationContext(srvCtx);
}
}
}
代码4:TestLoadClass
//取得注入实现类的JAVABEAN
package test;
import javax.servlet.http.HttpServletRequest;
import com.doit8.common.util.DateFormatImpl;
import com.doit8.common.util.IDateFormat;
import com.doit8.common.util.MyBeanFactory;
public class TestLoadClass {
IDateFormat datefomat;
private String datestr;
public TestLoadClass(HttpServletRequest request)
{
try {
//根据Spring配置的BeanName取得实现类(Spring配置见下配置文件)
datefomat=(DateFormatImpl)MyBeanFactory.getInstance(request,"DateFormat");
datestr=datefomat.getNowDate();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getDate()
{
return datestr;
}
}
配置文件1:web.xml
需要在web.xml文件中指定Spring的配置文件侦听类
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
配置文件2:applicationContext.xml
该配置文件指定实现类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="DateFormat" class="com.doit8.common.util.DateFormatImpl">
</bean>
</beans>
完成以上配置后就可以在Web应用中用到Spring配置中配置的实现类了。见下JSP代码
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="test.TestLoadClass"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'testjsp.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<%
TestLoadClass tlc=new TestLoadClass(request);
String datestr=tlc.getDate();
out.println(datestr);
%>
</body>
</html>
运行结果在页面上显示当前格式化后的日期