环境:MyEclipse6.0
步骤:建立一个Java工程,选择工程点击右键->MyEclipse->Add Spring Capabilities
写一个bean:
package spring.main.bean;
public class HelloBean {
private String helloWord;
public String getHelloWord() {
return helloWord;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
}
写Spring配置文件application.xml:
<?xml version="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/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="helloBean"
class="spring.main.bean.HelloBean">
<property name="helloWord">
<value>Hello!Epan Chen!</value>
</property>
</bean>
</beans>
写一个log4j.properties放在src目录下:
log4j.rootLogger=WARN, stdout
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
最后写一个测试类:
package spring.main.bean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class SpringDemo {
public static void main(String[] args) {
Resource rs = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean hello = (HelloBean)factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
运行SpringDemo,出现如下内容:
Hello!Epan Chen!