Spring @Value注解的注意事项


1,@Value注解不能用在静态成员上

2,使用@Value注解的类所在的包需要加入到组件扫描(context:component-scan)

3,使用@Value注解的类需要是 @Service,@Component,@Repository,@Controller 等注解才能被组件扫描到

4,在实例化包含@VAlue注解的类时,需要用 @Autowired ,如果New对象的话,则取不到值

applicationContext.xml

<!-- 自动注入配置文件 -->
<bean id="cfg" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
        </list>
    </property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="cfg" />
</bean>

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注