使用spring编写一个简单的例子
1.在eclipse里新建项目SpringStudy,项目下新建一个文件夹lib
里面拷贝log4j-1.2.13.jar,spring.jar,junit.jar,commons-logging.jar
2.项目propeties->Java Build Path 选择Libraries,将lib下的4个jar包通过,Add JARs加入到项目中(jar均可以在网上下载到。这步不操作,import时会有问题。通过设置环境变量也可以实现类似的效果)
3.在项目文件src下编写log4j配置文件log4j.properties
4.在项目文件src下新建 接口JDBCDriver
5.在项目文件src下新建 类MysqlJDBCDriver实现JDBCDriver
6.在项目文件src下新建 类OracleJDBCDriver实现JDBCDriver
7.在项目根目录下新建applicationContent.xml
8.在项目文件src下新建 类Main,用于程序启动的入口
9.eclipse里直接执行Main
会输出I am a MysqlJDBCDriver! (修改applicationContent.xml中的注入类可以输出I am a OracleJDBCDriver)
源码如下:
log4j.properties代码
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${countries.root}/WEB-INF/countries.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
JDBCDriver接口代码
public interface JDBCDriver {
public void jDBCDriver();
}
MysqlJDBCDriver类代码
public class MysqlJDBCDriver implements JDBCDriver {
public void jDBCDriver(){
System.out.print("I am a MysqlJDBCDriver!");
}
}
OracleJDBCDriver类代码
public class OracleJDBCDriver implements JDBCDriver {
public void jDBCDriver(){
System.out.print("I am a OracleJDBCDriver!");
}
}
Main类代码
import org.springframework.context.ApplicationContext;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Main
{
public static void main(String args[])
{
//ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContent.xml");
ApplicationContext ctx = new FileSystemXmlApplicationContext("/applicationContent.xml");
JDBCDriver hl = (JDBCDriver)ctx.getBean("JDBCDriver");
hl.jDBCDriver();
return ;
}
}
applicationContent.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="JDBCDriver" class="MysqlJDBCDriver"></bean>
</beans>