[英]Error while reading property file using @PropertySource in spring boot
[英]Spring Boot not reading from property file
我嘗試了Web上的每個選項,但無法通過以下方法設置值:
@Configuration
@PropertySource("classpath:application.properties")
public class MyDataSource {
@Value("${db.driver}")
private String DB_DRIVER;
@Value("${db.url}")
private String DB_URL;
@Value("${db.username}")
private String DB_USERNAME;
@Value("${db.password}")
private String DB_PASSWORD;
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
}
我的application.properties
位於main/resources
文件夾中,並且在調試模式下的變量中可以看到值。 但是在運行的應用程序上,它顯示Property ' ' must not be empty.
編輯:我不確定在第一種情況下可能是什么問題? 因此,按建議更改了application.property文件,並更改了以下代碼:
@Autowired
protected JdbcTemplate jdbcTemp;
public List<> getData(String id) {
return jdbcTemp.query("SELECT ........,new RowMapper());
}
但是獲取java.lang.NullPointerException:
如果您使用的是Spring Boot,則可以通過聲明一些條目來利用application.properties
文件:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
這樣,在Spring Boot中無需實現@Configuration
類來設置數據庫連接。
您可以在此處進一步了解: https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html
順便看看spring.io
對於Java配置,使用Environment
實例獲取屬性似乎是首選方法,因為默認情況下,不解析${..}
占位符。
您可以使用以下方式:
@Autowired
private Environment env;
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver");
.....
return dataSource;
}
春天吉拉的原因:
- 這是不一致的。 @PropertySource是ConfigurableEnvironment#addPropertySource的聲明性副本。 在后一種情況下,我們不添加PropertySourcesPlaceholderConfigurer,在前一種情況下這樣做是不一致的。 在所有(甚至大多數)情況下,這都不是用戶想要的。
- 完全有可能,甚至建議@Configuration類用戶完全放棄$ {...}屬性替換,而在@Bean方法中使用Environment#getProperty查找。 對於遵循此建議的用戶,PropertySorucesPlaceholderConfigurer的自動注冊在被注意到時會造成混亂,並且通常是不受歡迎的,因為它是一個更動人的部分。 是的,它的存在是良性的,但不是免費的。 PSPC必須訪問容器中的每個bean定義以查詢PropertyValues,僅在用戶使用Environment#getProperty方法時不執行任何操作。
- 它可以通過文檔解決(並且已經解決)。 正確使用@ PropertySource,PropertySourcesPlaceholderConfigurer和其他組件已經在Javadoc中針對@Configuration進行了全面的文檔記錄,並且很快就會有參考文檔。
嘗試從MySQL切換到MSSQL時,我也遇到了錯誤。 實際的問題是我忘記將MSSQL依賴項放入服務中。 我用mssql-jdbc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.