Java 在运行时将目录添加到类路径
在我当前的spring项目中,当我运行应用程序时,它在用户的主目录上创建了一个目录,在那里我存储了一些配置文件*.properties文件。在我的代码中,我以这种方式引用此文件:Java 在运行时将目录添加到类路径,java,spring,spring-mvc,classpath,spring-boot,Java,Spring,Spring Mvc,Classpath,Spring Boot,在我当前的spring项目中,当我运行应用程序时,它在用户的主目录上创建了一个目录,在那里我存储了一些配置文件*.properties文件。在我的代码中,我以这种方式引用此文件: private String getFilename() { return System.getProperty("user.home")+File.separator+".webapp"+File.separator+"webapp.preferences"; } 它允许我在任何操作系统中运行应用程序,而无
private String getFilename() {
return System.getProperty("user.home")+File.separator+".webapp"+File.separator+"webapp.preferences";
}
它允许我在任何操作系统中运行应用程序,而无需更改代码。我需要将这个目录添加到应用程序的类路径中,以允许我使用注释PropertySource,使用方法getproperty from Environment class或值注释来访问存储在文件中的属性
我使用spring boot,因此应用程序的起点是:
@Controller
@EnableJpaRepositories
@EnableAutoConfiguration
@ComponentScan(value="com.spring")
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
我还有WebAppInitializer、WebAppConfig和DispatcherConfig类来存储spring中的XML文件web.XML和dispatcher-config.XML处理的配置
任何人都能知道这是否可能,以及如何实现这一点
更新
根据评论中的建议,我将此bean添加到我的项目中:
@Bean
static PropertySourcesPlaceholderConfigurer property() throws Exception {
PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
String filename = System.getProperty("user.home")+File.separator+".webapp"+File.separator+"webapp.preferences";
File file = new File( filename );
if(file.exists())
propertyConfigurer.setLocation( new FileSystemResource( filename ) );
else {
if(file.mkdir()) {
FileOutputStream fos = new FileOutputStream( filename );
fos.close();
propertyConfigurer.setLocation( new FileSystemResource( filename ) );
}
}
return propertyConfigurer;
}
并尝试在我的pojo类中使用此选项:
@Input(label = "Titulo")
@Property(key = "geral.titulo")
@Value(value = "${geral.titulo}")
private String titulo;
但是,当我创建这个类的新实例时,字段不会收到注释所指示的值。我做错了什么?我验证文件及其属性是否存在。为什么不使用PropertyPlaceHolderConfigure并使用本地文件@Hannes好的,这应该足够了,但是您知道一些使用java类而不是xml的例子吗?