第一个Spring框架项目

  1. 新建一个Spring项目,代码如下:
package shen.liu.enmonster.com;

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

public class HelloWorld {
    private String name;
    public static void main(String args[]){
        //创建一个Spring的IOC容器对象(实例化Spring容器)
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        //从IOC容器对象中获取Bean实例   getBean()方法中的参数就是spring-config.xml文件中的id值
        HelloWorld helloworld = (HelloWorld) context.getBean("helloWorld");

        //调用sayHello()方法
        helloworld.sayHello("March");
    }
    public void setName(String name){
        this.name = name;
    }
    public void sayHello(String name){
        System.out.println(name + " hello!");
    }
}

其中spring-config.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 id="helloWorld" class="shen.liu.enmonster.com.HelloWorld"><!--这里需要注意的是带上包名的类-->
        <property name="name" value="Spring"></property>
    </bean>
</beans>
  1. 解释一下上面所说的spring-config.xml文件:
    属性值说明:

    • id 为bean容器取了一个名称,在配置文件中唯一。id属性不能包含特殊字符,是xml文件的本有属性,第一个字母小写
    • name 使用特殊字符而准备
    • class 指的是需要交给sprig管理的类,一般需要包含包名
      这个时候对象需要使用bean容器获取,而非创建。
  2. Bean容器的作用域
    • Bean容器的作用域主要有两种,一个是singleton,一种是prototype。singleton代表的是单例对象,而prototype代表的是非单例对象。
  3. Bean容器到底在什么时候实例化对象?
    • 当Bean容器的作用域是singleton时,在bean容器实例化的同时类对象就被实例化了。
    • 当Bean容器的作用域是prototype时,在bean容器实例化的时候,类对象未被实例化;只有在调用getBean()方法时,才实例化。
    • 但是我们可以通过修改配置文件,来延迟类实例化的进程。lazy-init(延迟实例化)选项。值可为“true/false”。
  4. init-method属性
    • init-method属性的值可以是Bean容器中被控制的类中所拥有的方法,一般使用init()方法。
      同样也可以设置destroy-method属性