天天看点

spring IOC set注入方式写helloworld

1.首先把spring框架所依赖的jar包下好。

2.build path 导入jar包,右键项目,build path–》add External Archives --》你下载好jar包所存放的位置

写一个HelloWorld 类,注意用bean时,如果你写了构造器,注意不要写带参的构造器。

package com.beans;

public class HelloWorld {
       private String name;

   
   // 这里的set方法对应bean中的propert name
   public void setName2(String name) {
      System.out.println("setName:"+name);
      this.name = name;
   }
    
   public void hello() {
       System.out.println("hello:"+name);
   }
   public HelloWorld() {
      // TODO Auto-generated constructor stub
      System.out.println("helloworld's constructor....");
   }
}      

写一个主类,开始的时候没用spring,直接主类调用setName赋值,后来用xml文件的setter注入的方式赋值。

package com.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    //创建一个HelloWorld 的对象
        //HelloWorld helloWorld=new HelloWorld();
        // 为name属性赋值
      //helloWorld.setName("xiongtong");
       //1.创建spring的IOC容器对象
    //ApplicationContext 代表IOC容器 是 BeanFactory 接口的子接口
    
    // ClassPathXmlApplicationContext: 是 ApplicationContext的实现类,从类路径下来加载配置文件
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //2.从IOC容器中获取bean实例
        HelloWorld helloWorld=(HelloWorld)ctx.getBean("helloWorld");
        System.out.println(helloWorld);
        //3.调用hello方法
        helloWorld.hello();
  }

}      

这是.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 配置bean 
    class :bean 的全类名,通过反射的方式在IOC容器中创建bean,所以要求必须要有无参的构造器
    id: 表示容器中唯一的id
    -->
    
    <bean id="helloWorld" class="com.beans.HelloWorld">
          <property name="name2" value="spring"></property>
    </bean>
    
</beans>