第一关:hello Spring
HelloWorld
:
package step1;
public class HelloWorld {
/********** Begin **********/
public void hello(){
System.out.println("Hello Spring");
}
/********** End **********/
}
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 id="helloworld" class="step1.HelloWorld"></bean>
</beans>
Test1
:
package step1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import step1.HelloWorld;
public class Test1 {
public static void main(String[] args) {
/********** Begin **********/
//1、创建Spring的IOC容器的对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从IOC的容器中获取Bean的实例
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloworld");
//3、调用方法
helloWorld.hello();
/********** End **********/
}
}
第二关:Spring IOC容器
package step2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import step2.HelloWorld;
public class MainApp {
public static void fun() {
/********** Begin **********/
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext2.xml");
boolean student = applicationContext.containsBean("student");
boolean helloworld = applicationContext.containsBean("helloworld");
Object bean = applicationContext.getBean("helloworld");
HelloWorld bean2 = applicationContext.getBean(HelloWorld.class);
HelloWorld bean3 = applicationContext.getBean("helloworld",HelloWorld.class);
System.out.println(student+"\n"+helloworld+"\n"+bean.toString()+"\n"+bean2.toString()+"\n"+bean3.toString());
/********** End **********/
}
}