Bean creation using Spel + hibernate

谁都会走 提交于 2019-12-11 23:39:19

问题


We are using Spring MVC + its built in support for uploading files. I want to set the maximum upload size utilizing SpEL. The problem is this value comes from our database. So in our old application code, we do a check once we have the file uploaded with the following:

appManager.getAppConfiguration().getMaximumAllowedAttachmentSize();

We then check the file to see if it is larger than this, and proceed based upon the size.

I'd like to replace that code with the following call in our servlet configuration like such:

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

The problem is that upon initialization I receive the following exception:

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

Is there any way to achieve this?


回答1:


I'd try a differnt approach:

  1. extend the org.springframework.web.multipart.commons.CommonsMultipartResolver
  2. add org.springframework.beans.factory.InitializingBean or use @PostConstruct to write a method that will call the appManager and set the maxUploadSize in beans initialization phase, after the configuration file was parsed and all dependencies were injected

For example like this:

public class MyMultipartResolver extends CommonsMultipartResolver {

    @Autowired
    private AppManager appManager;

    @PostConstruct
    public void init() {
        setMaxUploadSize(
            appManager.getAppConfiguration().getMaximumAllowedAttachmentSize());
    }
}

Still the maximim upload size will be set on the multipart resolver only once - during the application context initialization. If the value in database changes it will require an application restart to reconfigure the resolver for the new value.

Consider if You don't need to override the CommonsFileUploadSupport#prepareFileUpload() like this instead:

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:


There is another option that can be useful depending on your case. You can extend PropertiesFactoryBean or PropertyPlaceholderConfigurer and obtain some of the properties from your database.



来源:https://stackoverflow.com/questions/5749730/bean-creation-using-spel-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!