资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringContext加载方式的示例分析

这篇文章主要为大家展示了“Spring Context加载方式的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Spring Context加载方式的示例分析”这篇文章吧。

创新互联拥有一支富有激情的企业网站制作团队,在互联网网站建设行业深耕10年,专业且经验丰富。10年网站优化营销经验,我们已为上千多家中小企业提供了成都网站制作、成都网站建设、外贸营销网站建设解决方案,按需定制开发,设计满意,售后服务无忧。所有客户皆提供一年免费网站维护!

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);
  }

以上是“Spring Context加载方式的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


网站标题:SpringContext加载方式的示例分析
链接URL:http://cdkjz.cn/article/pcdies.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220