在 spring mvc 3.x 中存储自定义配置信息的好地方在哪里,我如何通过任何控制器全局访问该信息?
有内置的配置管理器吗?
我假设“自定义配置”是指代码读取/您/您的运营团队可以更新的配置文件?
一种简单的解决方案是使用 spring beans xml 配置文件并以爆炸方式部署您的战争。
创建一个配置java类:
// File: MyConfig.java ------------------------------------
public class MyConfig {
private String supportEmail;
private String websiteName;
// getters & setters..
}
将该类配置为 Spring bean 并在您的 spring beans xml 文件中设置其属性(也可以创建一个新文件并使用<import resource="..."/>
):
// File: root-context.xml ----------------------------------------
<beans ...>
...
<bean class="com.mycompany.MyConfig">
<property name="supportEmail" value="support@mycompany.com"/>
<property name="websiteName" value="Hello Site"/>
</bean>
...
</beans>
注入您的配置类(例如:在控制器中)
// File: HelloController.java ------------------------------------
@Controller
@RequestMapping("/hello")
public class HelloController {
@Autowired MyConfig config;
// ...
}
但是,对配置的更新需要重新部署/服务器重新启动
您也可以使用<context:property-placeholder>
.
它看起来像这样。
myapp.properties:
foo=bar
春豆xml:
<context:property-placeholder location="classpath:myapp.properties"/>
或者
<context:property-placeholder location="file:///path/to/myapp.properties"/>
控制器:
import org.springframework.beans.factory.annotation.Value;
...
@Controller
public class Controller {
@Value("${foo}")
private String foo;
如果要以编程方式获取属性,可以使用Environment
with @PropertySource
。
配置:
@Configuration
@PropertySource("classpath:myapp.properties")
public class AppConfig {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
控制器:
@Controller
public class Controller {
@Value("${foo}")
private String foo;
@Autowired
private Environment env;
@RequestMapping(value = "dosomething")
public String doSomething() {
env.getProperty("foo");
...
}
希望这可以帮助。