【发布时间】:2014-05-09 20:29:56
【问题描述】:
好的,我知道这个问题已经被问过好几次了,我已经尝试了他们建议的答案中的每一个解决方案,但还没有找到一个有效的解决方案,所以我希望这里的人能指出我正确的方向。
我正在尝试将 Spring 4 与以 Java 为中心的配置一起使用,但在从属性文件加载属性时遇到问题。我的最新方法几乎是逐字遵循 Spring 的文档 here,但即使这样也行不通。
这是我的 properties-config.xml 文件(位于我的类路径上的 /config 目录中):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:property-placeholder location="classpath:db.properties"/>
</beans>
这是我的网络应用初始化程序类(一个 sn-p,无论如何):
public class TestWebAppInitializer implements WebApplicationInitializer
{
@Override
public void onStartup(ServletContext container)
{
// Instantiate a new web application context
AnnotationConfigWebApplicationContext appContext =
new AnnotationConfigWebApplicationContext();
// Load the configurations
appContext.scan("com.acme.config");
appContext.refresh();
// Add the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
// Add the various listeners
container.addListener(new ContextLoaderListener(appContext));
container.addListener(new RequestContextListener());
}
}
最后是一个使用属性文件的小示例配置类:
package com.acme.config;
@Configuration
@ImportResource("classpath:config/properties-config.xml")
public class HibernateConfiguration
{
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password")
private String jdbcPassword;
@Bean(name = "dataSource")
public ComboPooledDataSource getDataSource() throws PropertyVetoException
{
// Define a variable to hold the result
ComboPooledDataSource ds = new ComboPooledDataSource();
System.out.println("URL: " + jdbcUrl);
System.out.println("Username: " + jdbcUsername);
System.out.println("Password: " + jdbcPassword);
// Set the properties for the data source
ds.setJdbcUrl(jdbcUrl);
ds.setUser(jdbcUsername);
ds.setPassword(jdbcPassword);
// Return the result
return ds;
}
}
最后但同样重要的是,属性文件:
jdbc.url=jdbc:hsqldb:hsql://localhost/test
jdbc.username=myusername
jdbc.password=mypassword
System.out.println 语句对每个阻止我的数据源设置的值都返回“null”。
谁能告诉我我做错了什么?谢谢!
【问题讨论】:
-
您打算向
properties-config.xml添加内容吗?如果没有,您只需将@PropertySources添加到@Configuration类。 -
顺便说一句,你有类型。应该是`@Value("${jdbc.password}")`
标签: java spring spring-mvc annotations properties-file