在Spring的IOC容器里配置Bean

xml 文件中通过 bean 节点来配置 bean

<bean id="helloWorld" class="com.spring.HelloWorld">
   <property name="userName" value="Spring"></property>
</bean>

idBean 的名称。

IOC 容器中必须是唯一的

id 没有指定,Spring 自动将权限定性类名作为 Bean 名字

id 可以指定多个名字,名字之间可用逗号、分号、或空格分隔

class:bean的全类名,通过反射的方式在IOC容器中创建Bean的实例,要求Bean中必须有无参的构造器,如要求在HelloWorld类中必须有无参的构造器

public HelloWorld(){
    System.out.println("HelloWorld's Constructor...");
}

Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用.

Spring 提供了两种类型的 IOC 容器实现.

BeanFactory: IOC 容器的基本实现.

ApplicationContext: 提供了更多的高级特性. BeanFactory 的子接口.

BeanFactory Spring 框架的基础设施,面向 Spring 本身;ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory

无论使用何种方式, 配置文件时相同的.

ApplicationContext 的主要实现类:

ClassPathXmlApplicationContext类路径下加载配置文件

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

FileSystemXmlApplicationContext: 从文件系统中加载配置文件

ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力

ApplicationContext 在初始化上下文时就实例化所有单例的 Bean

WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作

                                    

通过bean的Id从IOC容器中获取Bean的实例,利用ID定位到IOC容器中的Bean

完整源代码

配置文件application.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-->

    <bean id="helloWorld" class="com.spring.HelloWorld">
        <property name="userName" value="Spring"></property>
    </bean>
</beans>

HelloWorld类

public class HelloWorld {

    private String userName;

    public void setUserName(String userName) {
        System.out.println("SetName: " + userName);
        this.userName = userName;
    }

    public void hello(){
        System.out.println("Hello: " + userName);
    }

    public HelloWorld(){
        System.out.println("HelloWorld's Constructor...");
    }
}

Main类

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

public class Main {

    public static void main(String[] args) {
        /*//创建HelloWorld的一个对象
        HelloWorld helloWorld = new HelloWorld();
        //为name属性赋值
        helloWorld.setUserName("Tom");
        */
        //1、创建Spring的IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2、从IOC容器中获取Bean
        HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
        //3、调用hello方法
        helloWorld.hello();
    }
}

猜你喜欢

转载自blog.csdn.net/QuZDLvT/article/details/81410991