Put a spring bean into the Application scope?

2019-09-18 06:34发布

This is related this question:

I need to inject a Spring bean into the Tomcat application's scope at startup:

<beans:bean id="myUrl" class="java.lang.String" >
    <beans:constructor-arg type="java.lang.String">
        <beans:value>${my.registry.location:some.url}</beans:value>
    </beans:constructor-arg>
</beans:bean>

Is there a slick way to do this from the Spring XML configuration or do I need to override some servlet method (ugh)?

1条回答
地球回转人心会变
2楼-- · 2019-09-18 07:33

I thought I would post this in case it helps someone. Spring has a bean that will do this on initialization for you: ServletContextAttributeExporter.

You use it like this:

<bean id="myBean" class="java.lang.String" >
    <constructor-arg type="java.lang.String">
        <value>${some.property.value}</value>
    </constructor-arg>
</bean>

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
    <property name="attributes">
        <map>
            <entry key="myBean" value-ref="myBean" />
        </map>
    </property>
</bean>

You can then do something like this in your non-Spring aware JSP code (for example):

<div>
    Value of my bean is:  ${applicationScope.myBean}    
</div>
查看更多
登录 后发表回答