栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

浅谈Spring Context加载方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

浅谈Spring Context加载方式

Spring 加载方式

对于可执行文件方式,我们一般的加载Spring 配置的方式是

ClassPathXmlApplicationContext

 public static void main(String[] args) {
    ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
    DemoService demoService = (DemoService) xmlApplicationContext.getBean("demoService");
    String text = demoService.hello();
    System.out.println(text);
  }


  
  
  
  

从spring 3.0开始,开始使用注解的方式来进行spring 配置的注册

 public static void main(String[] args) {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    // 告诉要扫描的包,通常是应用的根目录的Application类
    annotationConfigApplicationContext.scan(Main.class.getPackage().getName());
    // 刷新上下文,使用得相应的bean注册成功
    annotationConfigApplicationContext.refresh();
    // 通过名称的方式获取相应的DemoService
    DemoService demoService = (DemoService) annotationConfigApplicationContext.getBean("demoService");
    String text = demoService.hello();
    System.out.println(text);
  }

demoService是定义的一个Service的名称,xml配置的方式也是可以设定好是否采用注解的方式进行扫描,如1中的

demoService 很简单,如下的方式

@Service(value = "demoService")
public class DemoService {
  public String hello() {
    return "hello world";
  }
}

Web应用的初始化

  1. web.xml配置方式
  2. 注解的方式

web.xml 配置方式

利用spring 自带的Servlet 进行初始注册

  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring/spring-context.xml
    
    1
    true
  
  
    SpringMVC
    /
  

利用 Listener进行注册 ,像Spring+structs,就是以这种方式来初始化上下文内容的

  
    
      org.springframework.web.context.ContextLoaderListener
    
  
  
    org.springframework.web.context.request.RequestContextListener
  

注解的方式

也是利用Servlet的方式来配置初始化参数,不过这次里要用基于注解的类AnnotationConfigWebApplicationContext,同时要注册Servlet

 @Override
  public void onStartup(ServletContext servletContext) throws ServletException {
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", DispatcherServlet.class);
    dispatcher.setInitParameter("contextConfigLocation", getClass().getName());
    dispatcher.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    dispatcher.addMapping("/*");
    dispatcher.setLoadonStartup(1);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号