spring 官网学习spring 知识

spring ioc container

只是转载bean的容器,

IoC , DI,

DI的方式

  • through constructor arguments 构造函数
  • arguments to a factory method, 工厂方式
  • properties that are set, 属性注入

IoC 容器

  • BeanFactory
  • ApplicationContext
  • WebApplicationCotext
  • DefaultListableBeanFactory
  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext

ApplicationContext与BeanFactory的区别

  • Easier integration with Spring’s AOP features,aop特性
  • Message resource handling (for use in internationalization), 消息处理,主要是国际化
  • Event publication , 事件发布, ApplicationEvent
  • Application-layer specific contexts such as the WebApplicationContext for use in web applications. 扩展web的容器

spring ioc container

image.png

构建应用上下文的方式

  • xml
  • java
  • java config
xml如何构建上下文
  1. 编写xml文件---services.xml



      
        
    

    
        
    

    



  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中,完成上下文构建的工作
}
}

配置元数据

  • Java-based configuration:
    @Configuration, @Bean, @Import, and @DependsOn annotations.
  • Annotation-based configuration:
    @Autowired,@Resource, @Inject
  • xml properties
    , ,

例子


// 注入其他xml文件
    
    
    

    
    

 
// 注入其他属性
        
        
        
    

获取Bean

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

例子

T getBean(String name, Class 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 userList = service.getUsernameList();

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

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

你可能感兴趣的:(spring 官网学习spring 知识)