2

我想实现一些全局配置静态类,它将包含所有应用程序的配置。另外我想从 xml 配置文件中注入这些参数。

第一种方法是创建配置类并将其注入到我需要的每个 bean/类中。但我不这样做,因为我的配置类包含所有应用程序的属性,并且到处都注入它......我不知道是什么)

第二种方法是尝试将 xml 配置值注入静态类,但它更像是解决方法..

哪种方式更好,为什么?

4

2 回答 2

1

我看到处理此类场景的最常见方法是将配置放入属性文件并通过PropertyPlaceHolderConfigurer.

例如,假设我有以下属性:

SO.properties

app.name=StackOverflow
app.mode=debug

在我的 Spring 配置文件中,我将包含context命名空间并通过PropertyPlaceholderConfigurerbean 引用它。

弹簧配置

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

创建PropertyPlaceholderConfigurerbean 后,我现在可以通过表达式语言引用属性,例如${app.name}在 bean 和配置文件中。

要将这些属性连接到 Spring bean,请使用 注释 bean 的字段@Value

@Component
public class MyBean{
   //This must be a Spring Bean


   //Wiring the value to the field
   @Value("#{app.name}")
   private String name;
}

PropertyPlaceholderConfigurer 文档

于 2013-08-12T09:28:21.377 回答
0

如果我没记错的话,你不能做这样的事情。您可以使用静态字段创建类,但不能向该字段注入属性。看看这个答案,也许对你有帮助:Spring: How to injection a value to static field?

于 2013-08-12T11:34:31.760 回答