前提:

已经导入spring的jar包。

环境:

Eclipse、JDK1.8、spring5.2.6

创建文件:

1.创建com.tutorialspoint包
2.创建HelloWorld类
3.创建MainAPP主类(void main)
4.创建Beans.xml

代码:

HelloWorld.java

  1. package com.tutorialspoint;
  2. public class HelloWorld {
  3. private String message;
  4. public void setMessage(String message){
  5. this.message = message;
  6. }
  7. public void getMessage(){
  8. System.out.println("Your Message : " + message);
  9. }
  10. }

MainApp.java

  1. package com.tutorialspoint;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class MainApp {
  5. public static void main(String[] args) {
  6. ApplicationContext context =
  7. new ClassPathXmlApplicationContext("Beans.xml");
  8. HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
  9. obj.getMessage();
  10. }
  11. }

Beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/context
  13. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  14. <bean id="helloWorld" name="hello" class="com.tutorialspoint.HelloWorld">
  15. <property name="message" value="Hello World!"/>
  16. </bean>
  17. </beans>

运行结果:

图片.png

要点:

xml文件中,property的name一定要对应字段,大小写不同也会导致失败。