我有一堆Spring bean,它们是通过注释从类路径中获取的,例如。

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
    // Implementation omitted
}

在Spring XML文件中,定义了一个PropertyPlaceholderConfigurer:

<bean id="propertyConfigurer" 
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/app.properties" />
</bean> 

我想将app. properties中的一个属性注入到上面所示的bean中。我不能简单地做一些

<bean class="com.example.PersonDaoImpl">
    <property name="maxResults" value="${results.max}"/>
</bean>

因为PersonDaoImpl没有出现在Spring XML文件中(它是通过注释从类路径中获取的)。我已经了解到以下内容:

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

    @Resource(name = "propertyConfigurer")
    protected void setProperties(PropertyPlaceholderConfigurer ppc) {
    // Now how do I access results.max? 
    }
}

但我不清楚我如何从ppc访问我感兴趣的财产?


当前回答

你也可以注释你的类:

@PropertySource("classpath:/com/myProject/config/properties/database.properties")

有一个这样的变量:

@Autowired
private Environment env;

现在你可以通过这种方式访问你的所有属性:

env.getProperty("database.connection.driver")

其他回答

你也可以注释你的类:

@PropertySource("classpath:/com/myProject/config/properties/database.properties")

有一个这样的变量:

@Autowired
private Environment env;

现在你可以通过这种方式访问你的所有属性:

env.getProperty("database.connection.driver")

在Spring 5中最简单的方法是使用@ConfigurationProperties https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/

在Spring 3.0.0M3中有一个新的注释@Value。@Value不仅支持#{…}表达式但是${…以及占位符

您可以在Spring 3中使用EL支持来实现这一点。例子:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties是一个隐式对象,strategyBean是一个bean名称。

再举一个例子,当您想从Properties对象中获取属性时,它可以工作。它还显示了你可以对字段应用@Value:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

这是我写的一篇关于这方面的博客文章,以获得更多信息。

春天道: 私人@ value (" $ {propertyName} ") 字符串propertyField;

是一种使用Spring的“PropertyPlaceholderConfigurer”类注入值的新方法。 另一种方法是打电话

java.util.Properties props = System.getProperties().getProperty("propertyName");

注意:对于@Value,你不能使用static propertyField,它只能是非静态的,否则它会返回null。为了解决这个问题,为静态字段创建了一个非静态setter,并在该setter之上应用@Value。