spring 官网 ioc- 1

2020-08-19  本文已影响0人  光小月

spring ioc container

只是转载bean的容器,

IoC , DI,

DI的方式

IoC 容器

ApplicationContext与BeanFactory的区别

spring ioc container

image.png

构建应用上下文的方式

xml如何构建上下文
  1. 编写xml文件---services.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
        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>

  1. 使用ClassPathXmlApplicationContext
// 支持多个xml资源, 拼接上去就可以了
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

//  构建2: classpath, 这个文件在resource文件夹下
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:services.xml");

另一种写法

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
java config构建
ApplicationContext context = new AnnotationConfigApplicationContext();

后台会将该类所在的路径作为基础扫描路径,当然包括本类会被扫描进。 
还会扫描对应的注解@Configuration, @Bean, @Component, @Import, @DependsOn

另一种写法

public class JavaConfigTest {
    public static void main(String[] arg) {
     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
     ctx.register(AppConfig.class); // 将本类注入到IoC中
      ctx.refresh(); // 刷新上下文,扫描并读取对应的class到beanDefinition中,完成上下文构建的工作
}
}

配置元数据

例子

<beans>
// 注入其他xml文件
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

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

 <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
// 注入其他属性
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>
</beans>

获取Bean

简答方式就是通过getBean的方式

例子

T getBean(String name, Class<T> requiredType)
--------------------------------------------------------

// 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();

写于 2020-08-12 23:42:11

PS: 若你觉得可以、还行、过得去、甚至不太差的话,可以“关注”一下,就此谢过!

上一篇 下一篇

猜你喜欢

热点阅读