带弹簧的动态属性名称

时间:2016-05-23 11:43:24

标签: spring spring-mvc

我正在使用spring 4 PropertyPlaceHolder:

<bean id="propertyConfigurer"
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/database.properties</value>
            <value>/WEB-INF/app.properties</value>    
            <value>/WEB-INF/cdservice.properties</value>            
        </list>
    </property> 

</bean>

从属性文件中我想读取我正在阅读的应用程序中的属性:

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${supporting.documents.location}")
    private String supportingDocumentsLocation;

    @Override
    public String removeFile(String xyz) {
       //Here I want to read property xyz which is dynamic
    }

}

与上面的代码一样,我可以使用@Value注释读取静态属性。 但是我如何读取像xyz这样动态的属性。请指教?

1 个答案:

答案 0 :(得分:1)

将Spring Environment注入到bean中,您可以读取任意属性:

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private Environment environment;

    @Value("${supporting.documents.location}")
    private String supportingDocumentsLocation;

    @Override
    public String removeFile(String xyz) {
        String value = environment.getProperty(xyz);
    }

}