每个人都知道,如果我们想要读取属性文件,我们可以这样做:
@Configuration
@PropertySource("classpath:/application.properties")
public class AppConfig {
@Value("${app.name}")
public String name;
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public PostService postService() {
return new PostServiceImpl(name);
}
}但是,现在我有了一个类似于SpringBoot的框架。它可以把Spring和Mybatis结合起来。
问题是前面的代码只能读取我的项目类路径文件,但是我需要使用我的框架读取属性文件项目。我是怎么做到的?
更新
我为大家感到遗憾。也许我说得不清楚,所以这是一幅画:

谢谢。
发布于 2019-03-09 08:09:42
Spring提供外部配置。这样,您就可以在不同的环境中运行应用程序。
参考链接:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
如果不喜欢application.properties作为配置文件名,则可以通过指定spring.config.name环境属性切换到另一个文件名。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:db.properties")
@PropertySource("classpath:project.properties")
public class DBConfiguration {
@Autowired
Environment env;
@Bean
public DBConnection getDBConnection() {
System.out.println("Getting DBConnection Bean for
App:"+env.getProperty("APP_NAME"));
DBConnection dbConnection = new DBConnection(env.getProperty("DB_DRIVER_CLASS"),
env.getProperty("DB_URL"), env.getProperty("DB_USERNAME"),
env.getProperty("DB_PASSWORD").toCharArray());
return dbConnection;
}
}
DB.properties:
#Database configuration
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:3306/Test
DB_USERNAME=root
DB_PASSWORD=root
project.properties:
APP_NAME=TEST APP发布于 2019-03-09 06:54:58
Spring框架可以从不同的位置读取外部配置文件。它可以从您的项目目录中读取配置文件,但是您需要删除这一行:
@PropertySource("classpath:/application.properties")这将它限制在应用程序类路径上。您可以检查这里以查看不同位置的spring读取配置文件。
发布于 2019-03-09 15:08:10
如果您只是希望自己从类路径中读取属性,则可以使用
Properties prop = new Properties();
InputStream input = this.getClass().getResourceAsStream("/application.properties")
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("foo"));https://stackoverflow.com/questions/55073597
复制相似问题