Bean creation using Spel + hibernate

2019-09-12 23:20发布

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?

2条回答
淡お忘
2楼-- · 2019-09-13 00:11

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;
    }
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-09-13 00:14

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.

查看更多
登录 后发表回答