Spring框架第一个HelloWorld程序
创建maven项目
创建HelloWorld类和Main类
HelloWorld类:
package Test;
public class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public void hello(){
System.out.println("hello:"+name);
System.out.println("Hello world!");
}
}
Main类:
package Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// 使用Spring框架后
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloWorld");
helloWorld.hello();
// 传统写法
// HelloWorld helloWorld = new HelloWorld();
// helloWorld.setName("Hello world!");
}
}
在resources文件夹中创建xml文件
在上一步创建的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/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置bean-->
<bean id="helloWorld" class="Test.HelloWorld">
<property name="name" value="Spring"></property>
</bean>
</beans>
运行
注意
必须等IDEA底部相关文件下载完成后在运行main方法