El primer programa HelloWorld en Spring Framework
Crea un proyecto maven
Crear la clase HelloWorld y la clase principal
Clase 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!");
}
}
Clase principal:
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!");
}
}
Crea un archivo xml en la carpeta de recursos
Configure el bean en el archivo xml creado en el paso anterior
<?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>
correr
Nota
Debe esperar la descarga de los archivos relevantes en la parte inferior de IDEA para ejecutar el método principal.