0

I would to read application.properties using @Value.

app.properties

JDBC_DRIVER =com.mysql.cj.jdbc.Driver
DB_URL =jdbc:mysql://127.0.0.1:3306/vetobooks?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
USER =root
PASS =a

main

package com.example.java_spring_java_example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;


@SpringBootApplication
    public class main {
            
        public static void main(String[] args) {
        
            
            ConfigurableApplicationContext context = SpringApplication.run(main.class, args);
            context.getBean(JDBCMysql.class);
            
        }

    }

JDBCMysql

package com.example.java_spring_java_example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class JDBCMysql {
      @Value("${JDBC_DRIVER}")
        public String JDBC_DRIVE;
       
        @Value("${USER}")
        public String USER;

        @Value("${PASS}")
        public String PASS;

        @Value("${DB_URL}")
        public String DB_URL;
    public void loadValue() {
      System.out.println(DB_URL+"-"+ USER+"-"+ PASS+"...");
    }
       }

I get null-null-null as a result. How can I get the real values?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Napster89
  • 63
  • 6
  • Does this answer your question? [How to access a value defined in the application.properties file in Spring Boot](https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot) – hamidreza75 Oct 19 '20 at 14:26
  • 1
    1. Use the spring managed isntance 2. `@Value` won't work on `static` fields. – M. Deinum Oct 19 '20 at 14:28
  • no i read this before :) , what i have to modify on my code? – Napster89 Oct 19 '20 at 14:28

2 Answers2

0

You can not access spring bean statically as you have done. Please access the bean as below in main method. And make method in JDBCMysql class non-static.

ConfigurableApplicationContext context = SpringApplication.run(main.class, args);
JDBCMysql jdbcmysql = context.getBean(JDBCMysql.class);
jdbcmysql.loadValue();

Moreover, I see space with every property. Remove space and it should work.

JDBC_DRIVER=com.mysql.cj.jdbc.Driver
DB_URL=jdbc:mysql://127.0.0.1:3306/vetobooks?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
USER=root
PASS=a
hiren
  • 1,742
  • 13
  • 20
0

I think the issue here is that you are using the static keyword.. You can do this but you must then have non static setters ..

i.e. Try this instead ..

public static String USER;
    
    @Value("${USER}")
    public void setUSER(String user) {
        .....
    }
mkane
  • 880
  • 9
  • 16