2

我有一个 .properties 文件。我可以根据需要将属性注入 bean。现在,我希望能够按名称搜索属性。

例子:

conf.properties:
a.persons=person1,person2,person3
a.gender=male

我可以通过使用注释来注入这些属性。例如,

private @Value("${a.persons}") String[] persons

除此之外,我想搜索给定名称的属性的值,但我不知道如何去做。一个例子是这样的:

properties.get("a.gender")

这应该返回字符串“男性”。

这真的可能吗?

更新:我使用PropertyPlaceholderConfigurer如下所示:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:META-INF/config/server.properties</value>
                <value>classpath:META-INF/config/ke/dev.properties</value>
            </list>
        </property>
    </bean>

我应该如何更改它以便可以将其注入到我的 bean 中?我将如何访问这些属性?提前致谢。

4

2 回答 2

1

答案取决于您如何配置这些属性的注入。

  • 如果您使用PropertyPlaceholderConfigurer,您可以将您的声明Properties为 bean 并将其注入PropertyPlaceholderConfigureras properties(而不是locations)。这样你也可以Properties直接将你的注入到你的 bean 中。

  • 如果您使用PropertySourcesPlaceholderConfigurer,您可以注入Environment到您的 bean 中,并且可以通过它获得属性。

于 2013-04-10T19:25:24.080 回答
1

根据@axtavt 的建议,我创建了如下所示的 bean,以帮助我搜索给定该属性名称的属性。我在我的解决方案中利用了@Environment 和@PropertySource。我使用的是 Spring 3.1,因此此解决方案可能不适用于 Spring 的早期版本。

@Configuration
@PropertySource( "/META-INF/config/ke/dev.properties" )
@Service( value = "keConfigurer" )
public class ServiceConfiguration {

    @Autowired
    private Environment env;

    public Environment getEnv() {
        return env;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }


}

我将这个 bean 注入到我希望在其中使用它的任何其他类中。例如:

public class TestClass {

    @Autowired
    private ServiceConfiguration cfg;

    String testProp = cfg.getEnv().getProperty("prop.name");
}

我希望它可以帮助别人。

于 2013-04-11T07:01:50.830 回答