![](/img/trans.png)
[英]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.