springmvc支持@Value

返回
Author Avatar
钢翼
2020-11-19
编程
63

有些旧项目用的是springmvc而不是springboot,配置注入五花八门,不方便维护,也不方便以后迁移springboot。

这里简单说明怎么在springmvc中使用@Value

1.首先添加application.properties

a=123456

2.在springmvc.xml中添加该文件的扫描


<context:property-placeholder location="classpath:application.properties" />

3.在spring.xml中添加bean

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="locations">
      <list>
         <value>classpath*:application.properties</value>
      </list>
   </property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
   <property name="properties" ref="configProperties" />
</bean>

4.代码中注入

//在类上添加注解
@PropertySource({"classpath:application.properties"})
class A{
  @Value("${a}")
  private String a;
}