第一步:下载Spring 、建立一个java工程,导入所需的jar包(spring.jar、log4j.jar以及lib\jakarta-commons目录下的所有jar包)
第二步:工程src目录下添加log4j.properties
# rootLogger是所有日志的根日志,修改该日志属性将对所有日志起作用
# 下面的属性配置中,所有日志的输出级别是info,输出源是console
log4j.rootLogger=info,console
# 定义输出源的输入位置是控制台
log4j.appender.console=org.apache.log4j.ConsoleAppender
# 定义输出日志的布局采用的类
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# 定义日志输出布局
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n
第三步:编写程序的主体代码:
package com.pb;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpring {
private String who;
private String profession;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public void print() {
System.out
.println(this.getWho() + "的职业是:" + this.getProfession() + "!");
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
helloSpring.print();
}
}
第四步:编写Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!--
- Root application context for the Countries application.
- Web-specific beans are defined in "countries-servlet.xml".
-->
<beans>
<bean id="helloSpring" class="com.pb.HelloSpring">
<property name="who" value="林冲"/>
<property name="profession" value="军人"/>
</bean>
</beans>
经过以上四步,一个简单的Spring例子就搞定了
运行结果:林冲的职业是:军人!