首先需要导入spring所需要的核心jar包
第一步:创建bean文件:HelloWorld.java
package com.demo;
public class HelloWorld {
public void sayHello() {
System.out.println("-----------Hello World ----------");
}
}
第二步:创建xml文件,进行配置所需调用的bean文件:
此处,我需要调用HelloWorld.java文件
<?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-4.3.xsd">
<bean id = "hello" class = "com.demo.HelloWorld"/>
</beans>
第三步: 调用ApplicationContext接口
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.demo.HelloWorld;
public class app {
public static void main(String[] args) {
ApplicationContext aContext = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = aContext.getBean("hello",HelloWorld.class);
helloWorld.sayHello();
}
}
这样就是spring的一大功能,IOC功能,控制反转,本身是有程序的 Object ob = new Object(); 通过程序new来调用对象,现在将创建对象的控制权移交给了spring容器。