Spring学习一:FirstDemo
IDE:MyEclipse 8.6,JRE1.6
一、新建一个Java Project,Project name:SpringStudy。然后右键选择MyEclipse->Add Spring Capabilities

二、在src目录下添加Log4j配置文件log4j.properties,参考配置如下:
log4j.rootLogger=WARN, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
如未添加会出现如下警告:WARN Please initialize the log4j system properly
三、编写第一个组件HelloBean:
package com.lifeng.spring.firstdemo.bean;import java.util.Date;public class HelloBean {private String helloWord;private Date date;public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public String getHelloWord() {return helloWord;}public void setHelloWord(String helloWord) {this.helloWord = helloWord;}}?? 再添加另一个Bean(该Bean为演示通过构造函数注入)
package com.lifeng.spring.firstdemo.bean;public class HelloBean2 {public HelloBean2(String name, String helloWord){this.helloWord = helloWord;this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getHelloWord() {return helloWord;}public void setHelloWord(String helloWord) {this.helloWord = helloWord;}String name;String helloWord;}??? 新建Config目录并添加配置文件firstDemo.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id = "hellobean" class = "com.lifeng.spring.firstdemo.bean.HelloBean"><property name="helloWord"><value>hello! first demo </value></property><property name="date"><!-- 引用其他bean --><ref bean = "dateBean"/></property></bean><bean id = "dateBean" class = "java.util.Date"></bean><bean id = "hellobean2" class = "com.lifeng.spring.firstdemo.bean.HelloBean2"><!-- 通过构造函数注入bean --><constructor-arg index = "0"><value>TT</value></constructor-arg><constructor-arg index = "1"><value>hello! </value></constructor-arg></bean></beans>
?四、FirstDemo的Main
package com.lifeng.spring.firstdemo;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import com.lifeng.spring.firstdemo.bean.HelloBean;import com.lifeng.spring.firstdemo.bean.HelloBean2;public class FirstDemoMain {/** * @param args */public static void main(String[] args) {ApplicationContext context = new FileSystemXmlApplicationContext("config/firstDemo.xml");HelloBean hello = (HelloBean) context.getBean("hellobean");System.out.println(hello.getHelloWord() + hello.getDate());HelloBean2 hello2 = (HelloBean2) context.getBean("hellobean2");System.out.println(hello2.getHelloWord() + hello2.getName());}}?
五、最后目录结构如下

?
?
测试结果:
hello! first demo Mon Sep 06 22:17:40 CST 2010
hello! TT
?