我试图通过自动装配环境变量来检索从 .yml 文件加载的属性,但出现空指针异常:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/example/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.NullPointerException
我想以编程方式创建一个 DataSource bean,同时将详细信息(用户名、密码、主机等)保留在配置文件中。这是我目前的设置:
@SpringBootApplication
@ImportResource({"classpath:controllers.xml"})
public class WebApplication{
public static void main(String[] args){
SpringApplication.run(WebApplication.class, args);
}
}
server:
port: 8080
database:
host: localhost
instance: db_instance
port: 3036
user: root
password: passkey
@Configuration
public class AppConfig {
@Autowired
private Environment environment;
@Bean
public DataSource dataSource() {
String url = "jdbc:mysql://" +
environment.getProperty("database.host") +
":" + environment.getProperty("database.port") +
"/" + environment.getProperty("database.instance") +
"?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true";
return DataSourceBuilder.create()
.driverClassName("com.mysql.jdbc.Driver")
.url(url)
.username(environment.getProperty("database.user"))
.password(environment.getProperty("database.password"))
.build();
}
}
我不偏爱 .yml 文件格式或使用环境变量。如果有不同/更好的方法来从 .yml 文件(或其他文件格式)获取数据,我愿意尝试。
翻阅古今
慕码人8056858
相关分类