有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring配置问题

我刚进入春天(我一个人,所以我没有人问愚蠢的问题)

我有几个关于Spring配置的问题(我使用的是3.0)。在阅读手册时,它说“主”配置是实例化所有bean的IoC容器之一。这样,当您实例化ApplicationContext时,您需要向它传递xml以及所有bean的配置位

无论如何,当您使用WebMVC框架时,您需要实例化DispatcherServlet,然后创建一个包含servlet配置的xml文件,并将您的内容放在那里。问题一:就这些吗?我的意思是,xml文件代表我可以传递给applicationcontext构造函数的相同文件,或者这是另一回事吗?如果我想配置整个applicationContext,我需要创建其他文件吗?怎么做

更进一步,我发现dispatcher servlet可能需要更多配置。比如,如果你想配置视图,如果你想解决视图bean和类似的情况,你必须编写一些配置文件。现在我看到很多教程都在讨论一个视图。xml文件。。。手册中甚至没有提到这一点(未找到cntrl+f)。我想知道这是程序员创建的然后包含在DispatcherServlet中的文件,还是某些组件读取的默认文件。。。我对此感到困惑

我想进一步了解整个ApplicationContext配置和dispatcherservlet之间的关系。如果有其他xml文件,我想知道在哪里可以找到关于它的资源,因为这些文档非常混乱

谢谢


共 (2) 个答案

  1. # 1 楼答案

    您还可以拆分applicationContext或servlet。xml,只需在web中定义多个文件。xml

    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        /WEB-INF/spring/spring-beans1.xml
        /WEB-INF/spring/spring-beans2.xml
      </param-value>
    </init-param>
    

    看看这个问题Use a ContextLoaderListener in accordance with DispatchServlet

    当我开始使用spring时,我需要了解的一件事是,应用程序上下文的默认范围是单例,而DispatcherServlet请求的默认范围。这意味着,尽管在应用程序启动时,ApplicationContext和DispatcherServlet是启动的,但如果从应用程序上下文中获取bean,则只要应用程序正在运行,它始终是同一个对象,而如果从servlet中获取bean。xml它总是为每个http请求新实例化

    http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes

    applicationContext在servlet中始终自动可用。xml

    您还可以使用http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.html自己获取应用程序上下文

  2. # 2 楼答案

    Anyway when you use the web MVC framework, you instantiate the DispatcherServlet, then you create an xml file with the name that includes the servlet config and you put your stuff there. Question one: is that all? I mean that xml file stands for the same files I could pass to the applicationcontext constructor or is that a different thing? Shall I create other files if I want to configure the whole applicationContext? How?

    虽然从理论上讲,您可以在一个单一的web应用程序上下文中定义所有bean,但按功能划分上下文通常被认为是良好的做法

    例如

    • 一个上下文将定义spring mvc web控制器
    • 可以定义服务层
    • 可以定义持久性/dao层

    您可以使用<import ...>声明将这些上下文导入到主web上下文中

    以下是spring参考资料中的相关部分: