@Value takes value in Controller

1. Use

  The @Value("${name}") annotation can get the name value in the custom properties file

Two, placement

  If it is only configured in applicationcontext.xml, there is no problem in obtaining it in service, but the value is obtained in the controller. If you want to obtain the value, you need to configure it again in spring-servlet.xml

!-- Define the environment variable file -->
    <bean id="propertyHolder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="locations">
            <list>
                <value>classpath*:/template.properties</value>
            </list>
        </property>
    </bean>

3. Reason

  The context defined in applicationcontext.xml is called the root context, namely WebApplicationContext, which is an interface class, to be precise, its actual implementation class is XmlWebApplicationContext. This is spring's IoC container, and the configuration of its corresponding bean definition is specified by the context-param tag in web.xml.

  After the contextLoaderListener listener is initialized, it starts to initialize the servlets configured in web.xml. This servlet can be configured with multiple ones. Taking the most common DispatcherServlet as an example, this servlet is actually a standard front-end controller for forwarding, matching, Process each servlet request. When the DispatcherServlet context is initialized, it will establish its own IoC context to hold springmvc-related beans. Each servlet holds its own context, that is, has its own independent bean space, and each servlet shares the beans defined in the root context. , you can directly refer to the bean defined in applicationcontext.xml by id.

  The definition of the controller is in the context defined by springmvc-servlet.xml, so when using @Value in the Controller to obtain the name value in the properties, it will only be searched in the context of the servlet. If it is not configured in springmvc-servlet.xml, it must be not found.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325087474&siteId=291194637