需求;使用spring框架,输出hello spring   其中spring使用spring框架进行设值注入

项目结构:

spring框架-ioc设置注入小demo_spring

 

 ApplicationContext.xml



1 <?xml version="1.0" encoding="UTF-8"?>
2 <!-- 引入spring框架的头文件 -->
3 <beans xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
7 <!-- 通过bean元素申明需要被容器管理的java类,id表示的是一个唯一标志,class表示的是具体的类 -->
8 <bean id="helloSpring" class="cn.springdemo.HelloSpring">
9 <!--property元素:给实例的属性进行赋值,实际上是调用的setWho()方法进行的复制操作,public void setWho(String
10 who) { 注意property中的name属性的实际上是setwho()方法中的参数 -->
11 <property name="who">
12 <!--属性具体的值 -->
13 <value>Spring</value>
14 </property>
15
16 </bean>
17
18
19 </beans>


 

package cn.springdemo;

public class HelloSpring {

  //定义who变量,他的值通过spring框架进行设值注入

  private String who;

  //定义打印方法输出一句完整的问候

  public void print(){

    System.out.println("Hello"+" "+this.getWho()+"!");

  }

  //set get 方法也是比较关键的

  public String getWho() {

    return who;

  }

  public void setWho(String who) {

    this.who = who;

  }


}

编写测试类:



1 package test;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5
6 import cn.springdemo.HelloSpring;
7
8 public class HelloSpringTest {
9 public static void main(String[] args) {
10 // 首先获取spring框架的配置文件,用ClassPathXmlApplicationContext这个类来读取配置文件
11 ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
12 "ApplicationContext.xml");// 由于是根路径,所以直接写一个文件名字就可以了
13 HelloSpring bean = (HelloSpring) classPathXmlApplicationContext
14 .getBean("helloSpring");// 配置文件中被管理的bean的id属性,返回的是一个object类型
15 bean.print();
16 }
17 }


运行结果;

spring框架-ioc设置注入小demo_xml_02

 

 

最后注意;使用bean元素定义一个组件,id属性:指定一个用来访问的唯一名称,name属性:指定多个别名,名字之间使用逗号、分号或则空格进行分割。