Spring学习(1)关于spring的上下文

本文的相关理解,是基于以下博主文章以及spring书籍总结而来

spring上下文 博客

文字型个人理解:https://www.cnblogs.com/chenbenbuyi/p/8166304.html

代码型技术解析:https://www.cnblogs.com/hello-shf/p/11006750.html

书籍:《Spring实战》第4版   P18-P19页  1.2.1 使用应用上下文

 

bean:spring 容器中的对象

spring 容器:负责管理bean 的生命周期

DI 依赖注入: 例如将B类所依赖的A类注入到B中,例如常用的:@Autowrite和@Resource 注解

BeanFactory:最简单的spring容器,只能提供基本的DI功能

应用上下文:(ApplicationContext)   继承了BeanFactory后派生而来的,是容器的一种,可以对bean进行管理操作

 

加载 应用上下文 的多种方式:

① AnnotationConfigApplicationContext:从一个或多个基于java的配置类中加载上下文定义,适用于java注解的方式;

② ClassPathXmlApplicationContext:从类路径下的一个或多个xml配置文件中加载上下文定义,适用于xml配置的方式;

③ FileSystemXmlApplicationContext:从文件系统下的一个或多个xml配置文件中加载上下文定义,也就是说系统盘符中加载xml配置文件;

④ AnnotationConfigWebApplicationContext:专门为web应用准备的,适用于注解方式;

⑤ XmlWebApplicationContext:从web应用下的一个或多个xml配置文件加载上下文定义,适用于xml配置方式。

 

例如:

1.创建一个xml文件,如:applicationContext.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"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        //中间部分是你自己配置的所有bean
</beans>

2. 加载上下文 ,获取bean信息

public class Test {
    public static void main(String[] args) {
        //加载项目中的spring配置文件到容器
//        ApplicationContext context = new ClassPathXmlApplicationContext("resouces/applicationContext.xml");
        //加载系统盘中的配置文件到容器
        ApplicationContext context = new FileSystemXmlApplicationContext("E:/Spring/applicationContext.xml");
        //从容器中获取对象实例
        Man man = context.getBean(Man.class);
        man.driveCar();
    }
}

或使用 web.xml 加载:

 <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值