Java Spring读取类路径之外的属性文件
我在tomcat文件夹中有一个属性文件。我正试图读取属性文件内容,如下所示。但我得到的属性值为空 文件路径没有任何问题Java Spring读取类路径之外的属性文件,java,spring,properties,Java,Spring,Properties,我在tomcat文件夹中有一个属性文件。我正试图读取属性文件内容,如下所示。但我得到的属性值为空 文件路径没有任何问题 @ComponentScan(basePackages = "org.sakaiproject.log.api") @Configuration @PropertySource(name = "props", value = { "file:/home/tomcat-sakai-7.0.55/sakai/local.properties", "f
@ComponentScan(basePackages = "org.sakaiproject.log.api")
@Configuration
@PropertySource(name = "props", value = {
"file:/home/tomcat-sakai-7.0.55/sakai/local.properties",
"file:/home/tomcat-sakai-7.0.55/sakai/sakai.properties" })
public class SpringCryptoContext {
@Value("${aes.encryption.cipherString}")
private static String cyperString;
public SpringCryptoContext() {
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(
SpringCryptoContext.class);
System.out.println(cyperString);
}
}
编辑:
我创建了一个单独的类,并按如下方式加载属性
@Service
@PropertySource(name = "locations", value = {
"file:/home/nirmala/projects/iml/tomcat-sakai-7.0.55/sakai/local.properties",
"file:/home/nirmala/projects/iml/tomcat-sakai-7.0.55/sakai/sakai.properties" })
public class CryptoToolImpl implements CryptoTool {
private Cipher cipher = null;
private Key key = null;
@Value("${pii.encryption.cipherString}")
private String cipherString = "";
public static final Logger log = Logger.getLogger(CryptoToolImpl.class);
public IMLCryptoToolImpl() {
try {
fixKeyLength();
cipher = Cipher.getInstance(cipherString);
key = KMSKeyStoreSingleton.getInstance().getPrivateKey();
} catch (Exception e) {
log.error("Error in initializing CryptoToolImpl : "
+ e.getMessage());
}
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
但是我得到了以下错误
初始化CryptoToolImpl时出错:转换格式无效:
请在配置类中添加以下bean:-
//To resolve values using the @Value
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigDev() {
return new PropertySourcesPlaceholderConfigurer();
}
更新
静态在这种情况下不起作用,您需要执行以下操作:-
添加以下代码:-
@Value("${aes.encryption.cipherString}")
private String cyperString;
public String getCypherString(){
return this.cyperString;
}
这只是一个示例,但您使用的是static,因为您在main方法中访问它,即static
,对于访问变量,您将其标记为static
问题在于,静态变量是一个类变量,当代码到达系统的行时,该类变量没有属性。对于该变量,out
,此时-spring仍在进行内部初始化等
当您使用spring进行实例化时,您正在访问/使用变量作为非spring框架。它必须是单向的
我建议使用一个单独的类将这些变量加载到上下文中,可能是一些标有@Component
的类,或者更具体地说是@Service
下面的内容应该会有所帮助
@Configuration
@PropertySources(value={
@PropertySource(value="file:${catalina.home}/sakai/local.properties"),
@PropertySource(value="file:${catalina.home}/sakai/sakai.properties")
})
public class SpringCryptoContext {
@Value("${aes.encryption.cipherString}")
private String cyperString;
}
您确定用户tomcat正在使用,是否具有文件的读取权限?@Evgeni Dimitrov yes files have read access您不能在静态
字段上使用@Value
。仍然为空。您可以检查属性键的拼写吗文件路径和属性键没有问题我读取了与spring属性文件读取相关的所有文章。在所有这些文章中,属性文件都是空的在项目的类路径中定义。@kakabali仍为null