无法从属性文件中使用@Value(“ $ {database.name}”)获取值

@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 ----即将出现在控制台中。启动应用程序时必须从属性文件中获取价值。有什么方法可以获取价值?

w690979631 回答:无法从属性文件中使用@Value(“ $ {database.name}”)获取值

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

这是因为在Spring中,这些字段是在默认构造函数调用之后初始化的,因此,您只应在构造函数调用之后访问它,请尝试以下操作:

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

侧注优先:

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:

不在构造器中检查,而是在后构造中检查,或者是否在谈论@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);
     }
}
本文链接:https://www.f2er.com/3154135.html

大家都在问