spring 容器几种启动方式

49 篇文章 1 订阅

1、spring ioc容器web项目中通过servlet机制启动spring容器

具体启动实现方式:

<!-- Spring监听器 -->
<listener>
    <description>Spring监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

由于web容器在启动的时候实现了对servlet的监听,当在web容器中存在servlet的实现的时候,会自动执行其init方法进行ioc容器的启动

2、通过XmlBeanDefinitionReader 进行spring ioc 容器启动

<?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: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必须是一个class类,不能是一个接口或者抽象类-->
    <bean id="car1" class="com.youx.qd.Car"

</beans>
public class BeanFactoryTest{
  private XmlBeanDefinitionReader;
  static {
    ResourcePatternresolver resolver = new PathMatchingResourcePatterResolver();
    Resource res = resolver.getResource("classpath:beans.xml");
    //创建一个工厂
    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    //启动spring ioc容器
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
    //加载配置文件
    reader.loadBeanDefinitions(res);

    Car car = factory.getBean("car",Car.class);
  }
}

3、使用ClassPathXmlApplicationContext进行 sprig ioc容器的启动

//启动容器
public static final ClassPathXmlApplicationContext CONTEXT = new ClassPathXmlApplicationContext("spring-kafkaConsumer.xml");
//获取一个bean(实例化对象)
KafkaConsumerService kafkaConsumerService = (KafkaConsumerService) CONTEXT.getBean("kafkaConsumerService");

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值