1. 导入Spring核心JAR包 和 所依赖的Commons-logging日志包
2. 创建HelloWord实体类
package org.spring;
public class HelloWord {
private String name;
public HelloWord(String name) {
System.out.println(name);
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void hello() {
System.out.println(this.name);
}
}
3. 在类路径下创建Spring配置文件:applicationContext.xml,并配置Bean
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">
<beans>
<bean id="helloWord" class="org.spring.HelloWord">
<!--给HelloWord成员属性name赋值为hellowird!-->
<property name="name" value="helloWord!"></property>
</bean>
</beans>
</beans>
4. 初始化Spring IOC 容器,获取Bean并使用
package org.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//创建Spring容器对象 从类路径下查找Spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(applicationContext);
//创建Spring容器对象 从文件系统中 寻找 Spring配置文件
/*
String path = "F:\\EclipseWorkspace\\1.SpringHelloWord\\src\\applicationContext.xml";
applicationContext = new FileSystemXmlApplicationContext(path);
System.out.println(applicationContext);
*/
//获取SpringBean
HelloWord helloWord = (HelloWord) applicationContext.getBean("helloWord");
helloWord.hello();
}