[英]Why I fail to use properties from application.properties file in Spring Boot?
Why I fail to use data from application.properties
in the PostDao
class?为什么我无法在
PostDao
类中使用application.properties
中的数据? Properties just not injected and DATABASE_URL and other variables are null
.未注入的属性和 DATABASE_URL 和其他变量为
null
。
PostDao.java
is the class (src.main.java.site.model.PostDao) where I try to use properties. PostDao.java
是我尝试使用属性的类 (src.main.java.site.model.PostDao)。
@Component
public class PostDao
{
@Value("${url}") public static String DATABASE_URL;
@Value("${user}") public static String USER;
@Value("${password}") public static String PASSWORD;
}
Here is my application.peoprerties
file which stays in the resources directory这是我的
application.peoprerties
文件,它位于资源目录中
url=jdbc:postgresql://localhost:5432/news
user=postgres
password=123
Here is my config file (src.main.java.site.NewsSiteApplication)这是我的配置文件(src.main.java.site.NewsSiteApplication)
@SpringBootApplication
public class NewsSiteApplication
{
public static void main(String[] args)
{
SpringApplication.run(NewsSiteApplication.class, args);
}
}
You can't inject in a static variable.您不能注入静态变量。 You need a Spring-managed Bean for that.
为此,您需要一个 Spring 管理的 Bean。 Try the following:
请尝试以下操作:
@Component
public class PostDao {
@Value("${url}") public String databaseUrl;
@Value("${user}") public String user;
@Value("${password}") public String password;
}
As pointed out by @Turing85 (thanks for the hint ;) ), only constants should be written in UPPER_SNAKE_CASE
, hence I changed the variables name.正如@Turing85 所指出的(感谢提示;)),只应在
UPPER_SNAKE_CASE
写入UPPER_SNAKE_CASE
,因此我更改了变量名称。
Alternatively, you can do the following, the setter method will handle for the injection:或者,您可以执行以下操作,setter 方法将处理注入:
@Component
public class PostDao
{
public static String DATABASE_URL;
@Value("${url}")
public void setUrlStatic(String name){
PostDao.DATABASE_URL = name;
}
// And others..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.