The first HelloWorld program in Spring framework
Create a maven project
Create HelloWorld class and Main class
HelloWorld class:
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 class:
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!");
}
}
Create an xml file in the resources folder
Configure the bean in the xml file created in the previous step
<?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>
run
note
You must wait for the download of the relevant files at the bottom of IDEA to run the main method