简体   繁体   中英

How to access properties @value using spring boot

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?

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

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 ..

ie Try this instead ..

public static String USER;
    
    @Value("${USER}")
    public void setUSER(String user) {
        .....
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM