【问题标题】:Unable to get value using @Value("${database.name}") from properties file无法使用属性文件中的 @Value("${database.name}") 获取值
【发布时间】:2020-03-02 15:41:07
【问题描述】:
@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 ---- 即将进入控制台。必须在启动应用程序时从属性文件中获取值。有没有办法获取价值?

【问题讨论】:

  • 该值将在调用构造函数之后设置,因此尝试在构造函数中打印它总是会导致null
  • 您还可以为该值添加另一个属性。既然有两个字段,它们的意思真的一样吗?那么它可能应该是一个字段,否则它可能应该是具有相同值的不同属性...
  • 感谢 cmets M. Deinum & dertoni 。我真的在这里学到了一些概念。

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


【解决方案1】:

先附注:

Spring boot只有放入才能自动读取application.properties

  • src/main/resources
  • src/main/resources/config文件夹

确保它确实在那里。

现在真正的问题是:

您正在尝试访问 构造函数中的属性,这不是 spring 的工作方式:

Spring 首先创建对象(通过调用其构造函数),然后才注入其字段。

所以你有两种方法:

选项 1:

为你的 bean 使用构造函数注入(我看到你使用 @Configuration,但这个建议更适合真正的 bean,只是在那里更有意义):

@Component
class MyClass {

  public MyClass(@Value({"db.name"} String dbName) {
  ....
  }
}

选项 2:

不要在构造函数中检查,而是在 postconstruct 中检查,或者如果您正在谈论 @Bean 注释方法中的配置:

@Configuration
public class MyConfig {

     @Value("${db.name}")
     private String dbName;


     @Bean
     public SomeBean someBean() {
         // here dbName should be accessible
         return new SomeBean (dbName)
     }  

     // alternatively you can inject dbName like this:

     @Bean
     public SomeOtherBean someOtherBean(@Value("${db.name}") String dbName) {
         return new SomeOtherBean(dbName);
     }
}

【讨论】:

  • 嗯,这不完全正确...属性可以在很多地方,不仅在 src/main/resources...见docs.spring.io/spring-boot/docs/current/reference/html/…
  • 是的,当然,你是对的。我的意思是“application.properties”不在广泛存在的测试和默认值中。当然,除了默认值之外的任何东西都需要额外的配置......
【解决方案2】:

这是因为Spring中的字段是在默认构造函数调用之后初始化的,所以你应该只在构造函数调用之后才访问它,试试这个:

 @PostConstruct
 public void postConstructorMethod(){
    dbname2 = dbname;
    System.out.println(" ::::: Got Data from properties file Successfully ::::: " + dbname2);
 }

【讨论】:

  • 感谢 Mustahsan。这对我来说真的很有帮助。我最初的要求是在启动应用程序并通过@Autowired 将该连接传递给不同的服务类时创建一个 Cosmos DB 连接。所以,我在这里发布了一个我遇到问题的示例案例。非常感谢。
  • @Balaji211 如果这解决了你的问题,你可以考虑接受这个答案stackoverflow.com/help/someone-answers
【解决方案3】:

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

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

@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);
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 2013-05-07
    • 2017-09-02
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多