2.创建lib目录;导入下图的jar包,其中common-logging.jar不是spring本身包含的包;
3.把jar包 add to build path;
4.建立一个HelloWorld类:
package com.ksk.spring;
public class HelloWorld {
private String userName;
public void setUserName(String userName) {
System.out.println("setName" + userName);
this.userName = userName;
}
public void hello(){
System.out.println("你好"+userName);
}
public HelloWorld(){
System.out.println("HelloWorld...Constructor");
}
}
5.编写配置文件applicationContext.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.xsd"> <!-- 配置Bean --> <bean id="helloWorld" class="com.ksk.spring.HelloWorld"> <property name="userName" value="spring"></property> </bean> </beans>
6.编写Main.java:
package com.ksk.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//创建一个HelloWord的一个对象
//HelloWord helloWorld = new HelloWord();
//为name属性赋值
//helloWorld.setUserName("ksk");
//1.创建Spring的IOC容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取Bean实例
HelloWorld helloWord = (HelloWorld) ctx.getBean("helloWorld");
//3.调用hello()方法
helloWord.hello();
}
}
7.小结:创建spring容器时,对配置文件的bean进行初始化,会调用构造器,会调用set方法对属性进行赋值。
转载于:https://blog.51cto.com/519524666/1572764