前提:
已经导入spring的jar包。
环境:
Eclipse、JDK1.8、spring5.2.6
创建文件:
1.创建com.tutorialspoint包
2.创建HelloWorld类
3.创建MainAPP主类(void main)
4.创建Beans.xml
代码:
HelloWorld.java
package com.tutorialspoint;public class HelloWorld {private String message;public void setMessage(String message){this.message = message;}public void getMessage(){System.out.println("Your Message : " + message);}}
MainApp.java
package com.tutorialspoint;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp {public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext("Beans.xml");HelloWorld obj = (HelloWorld) context.getBean("helloWorld");obj.getMessage();}}
Beans.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" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><bean id="helloWorld" name="hello" class="com.tutorialspoint.HelloWorld"><property name="message" value="Hello World!"/></bean></beans>
运行结果:
要点:
xml文件中,property的name一定要对应字段,大小写不同也会导致失败。
