【问题标题】:Bean creation using Spel + hibernate使用 Spel + hibernate 创建 Bean
【发布时间】:2011-08-10 14:53:51
【问题描述】:

我们正在使用 Spring MVC + 它内置的上传文件支持。我想使用 SpEL 设置最大上传大小。问题是这个值来自我们的数据库。因此,在我们的旧应用程序代码中,一旦我们上传了包含以下内容的文件,我们就会进行检查:

appManager.getAppConfiguration().getMaximumAllowedAttachmentSize();

然后我们检查文件看它是否比这个大,并根据大小继续。

我想用我们的 servlet 配置中的以下调用替换该代码,如下所示:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver>
    <property name="maxUploadSize" value="#{appManager.getAppConfiguration().getMaximumAllowedAttachmentSize()}" />
</bean>

问题是在初始化时我收到以下异常:

Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session

有什么办法可以做到吗?

【问题讨论】:

    标签: hibernate spring file-upload spring-mvc spring-el


    【解决方案1】:

    我会尝试不同的方法:

    1. 扩展org.springframework.web.multipart.commons.CommonsMultipartResolver
    2. 添加org.springframework.beans.factory.InitializingBean或使用@PostConstruct编写一个方法,在解析配置文件并注入所有依赖项后,在bean初始化阶段调用appManager并设置maxUploadSize

    例如这样:

    public class MyMultipartResolver extends CommonsMultipartResolver {
    
        @Autowired
        private AppManager appManager;
    
        @PostConstruct
        public void init() {
            setMaxUploadSize(
                appManager.getAppConfiguration().getMaximumAllowedAttachmentSize());
        }
    }
    

    最大上传大小仍然只会在多部分解析器上设置一次 - 在应用程序上下文初始化期间。如果数据库中的值发生更改,则需要重新启动应用程序才能为新值重新配置解析器。

    考虑您是否不需要像这样覆盖CommonsFileUploadSupport#prepareFileUpload()

    public class MyMultipartResolver extends CommonsMultipartResolver {
    
        @Autowired
        private AppManager appManager;
    
        @Override
        protected FileUpload prepareFileUpload(String encoding) {
            FileUpload fileUpload = super.prepareFileUpload(encoding);
            fileUpload.setSizeMax(
                appManager.getAppConfiguration().getMaximumAllowedAttachmentSize());
            return fileUpload;
        }
    }
    

    【讨论】:

      【解决方案2】:

      根据您的情况,还有另一个有用的选项。您可以扩展PropertiesFactoryBeanPropertyPlaceholderConfigurer 并从您的数据库中获取一些属性。

      【讨论】:

        猜你喜欢
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-04
        • 1970-01-01
        相关资源
        最近更新 更多