java - 无法使用 @Value ("${database.name}"从属性文件中获取值

标签 java spring spring-boot spring-mvc properties-file

@Configuration
public class Config {

    @Value("${database.name}")
    private String dbname;

    public String dbname2;

    public Config(){
        dbname2 = dbname;
        System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
    }
}
@Service
public class MainService {

    @Autowired
    Config config;

    public String getPropertiesData(){

        String data = "Properties Data is " + config.dbname2;

        return data;
    }
}

application.properties 文件中的数据:

server.port=8081
database.name=azurecosmosDB

堆栈跟踪在启动应用程序时位于下方:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.0.RELEASE)

2019-11-06 13:10:21.106  INFO 13328 --- [  restartedMain] com.example.demo.DemoApplication         : Starting DemoApplication on LP-5CD921DY4D with PID 13328 (C:\Users\BalajiChe\Desktop\STOMP\demo\target\classes started by BalajiChe in C:\Users\BalajiChe\Desktop\STOMP\demo)
2019-11-06 13:10:21.113  INFO 13328 --- [  restartedMain] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-11-06 13:10:21.247  INFO 13328 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-11-06 13:10:21.247  INFO 13328 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-11-06 13:10:27.732  INFO 13328 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2019-11-06 13:10:27.763  INFO 13328 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-11-06 13:10:27.763  INFO 13328 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
2019-11-06 13:10:28.335  INFO 13328 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-11-06 13:10:28.336  INFO 13328 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 7089 ms
 ::::: Got Data from properties file Successfully ::::: null
2019-11-06 13:10:30.395  INFO 13328 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-11-06 13:10:31.212  INFO 13328 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-11-06 13:10:31.382  INFO 13328 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-11-06 13:10:32.063  INFO 13328 --- [  restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2019-11-06 13:10:32.128  INFO 13328 --- [  restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2019-11-06 13:10:32.168  INFO 13328 --- [  restartedMain] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2019-11-06 13:10:32.523  INFO 13328 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2019-11-06 13:10:32.529  INFO 13328 --- [  restartedMain] com.example.demo.DemoApplication         : Started DemoApplication in 12.299 seconds (JVM running for 14.621)

另外, 成功从属性获取数据到文件::::null ---- 出现在控制台中。必须在启动应用程序时从属性文件中获取值。有什么办法可以得到这个值吗?

最佳答案

正如@Mustahsan 所说,您无法访问在构造函数中注入(inject)到字段中的值,因为注入(inject)发生在构造之后。

但是,如果您想使用构造函数,那么您可以使用构造函数注入(inject)来代替字段注入(inject),无论如何这通常被认为是更好的做法:

@Configuration
public class Config {
    public String dbname2;

    public Config(@Value("${database.name}") String dbname){
        dbname2 = dbname;
        System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
    }
}

关于java - 无法使用 @Value ("${database.name}"从属性文件中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725345/

相关文章:

java - 当我使用 spring boot 运行项目时。它运行良好。但是当我将它部署到tomcat中时。我收到低于书面的异常

java - 将 Maven 测试日志重定向到 Eclipse 控制台

java - java中如何实现队列和优先级队列

java - 解析两个同名元素 - Pull Parser

java - 插入LinkedList,然后按ID号升序排序

java - GWT 服务异常日志记录的最佳实践

java - 使用 Disruptor 和 Executors 在 Java 中设计 Orchestrator

java - 使用ResponseStatusException类进行错误处理

java - 如何从 Google Cloud Storage 下载文件并将其返回到 Spring Controller 中

java - Spring Batch - 在读取器处理器和写入器之间传递所有数据