IoC容器(一)

56 阅读1分钟

org.springframework.context.ApplicationContext接口用于代表Spring IoC容器,负责实例化,配置以及分配beans。

XML通过<beans/>标签下的<bean/>标签配置beans。

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

Java注解通常是在@Configuration注释的类中定义@Bean注释的方法来定义beans.

@Configuration
public class Config {   
    @Bean   
    public Dog dog() {      
        return new Dog();   
    }
}

容器加载多个xml配置文件

方式一:

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

方式二:

<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/> <!-前导斜杠会被忽略,推荐不加前导斜杠-->

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

可以通过"../"引用父目录的配置文件,但是不推荐这么做。

不推荐这种用法classpath:../services.xml

可以通过ApplicationContextT getBean(String name, Class<T> requiredType)检索bean实例。示例如下:

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

通常你并不需要使用getBean方法。

通过GenericApplicationContext配合不同的reader代理可以实现加载不同的配置。以下是通过XmlBeanDefinitionReader加载Xml配置文件的例子:

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();

通过GroovyBeanDefinitionReader加载配置文件的例子:

GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
context.refresh();