【问题标题】:How to dump autowired spring beans to a xml configuration file?如何将自动装配的 spring bean 转储到 xml 配置文件?
【发布时间】:2013-11-07 08:02:17
【问题描述】:

我正在使用带有 spring-mvc 和 spring-security 的 @Autowired 注释,它可以工作,但是 webapp 启动非常慢,每次大约 1 分钟,因为 spring-mvc 和 spring-security 扫描了两次所有自动装配的类和班级总数约500个。 有什么建议可以加快扫描时间吗?还是静态xml配置更好?

在 web.xml 中

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/rest-servlet.xml
    </param-value>
</context-param>
    <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

    <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

    <servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
    <servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
    ....

在 rest-sevlet.xml 中

    <context:component-scan base-package="com.mycomp" />
<mvc:annotation-driven />
<mvc:interceptors>
    ....
    </mvc:interceptors>
<import resource="classes/config/applicationContext-security-base.xml"/>
<import resource="classes/config/applicationContext-security.xml"/>

<import resource="classes/config/spring-aop.xml"/>
<!-- i18n --> 
<import resource="classes/config/spring-locale.xml"/>

【问题讨论】:

  • 为什么类会被扫描两次?! Spring Security 仅扫描已定义的 bean(即上下文中的 @Components)。组件扫描扫描 bean 的类路径。如果配置错误,您可能会有重复的 bean。其次,为什么启动时间是个问题?无论如何发布一些配置和你的 web.xml。
  • 使用分析器查看时间的去向。 Spring 通常启动很快,但您的一些 bean 可能需要一些时间(例如 Hibernate?)
  • 扫描两次它由 spring-mvc sevlet (rest-servlet) 和 spring-security 过滤器引起,我认为。他们都需要一个单独的弹簧上下文。
  • 就像问题linkthere

标签: xml spring spring-mvc annotations


【解决方案1】:

首先不要两次加载您的配置。目前ContextLoaderListenerDispatcherServlet 都加载相同的配置文件。结果重复 bean 实例、重复扫描(以及未来的内存问题、奇怪的事务问题等)。

您的配置需要拆分。您的ContextLoaderListener 应该只将一般的东西加载到您的应用程序(服务、存储库、数据源等)。反过来,DispatcherServlet 应该包含/加载仅与 Web 相关的内容,例如 (@)ControllersViewResolversViews、mvc 配置等。

还要注意组件扫描,不要落入每个人都会做的陷阱。如果将 same comonent-scan 添加到每个配置文件,这将导致 bean 重复(每个 bean 都会被实例化两次)。因此,请确保您的 ContextLoaderListener' scans for everything but controllers and that yourDispatcherServlet` 仅扫描与 Web 相关的内容(例如控制器)。

【讨论】:

    猜你喜欢
    • 2020-09-09
    • 2015-12-23
    • 2015-08-06
    • 2012-10-25
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2018-09-18
    相关资源
    最近更新 更多