简体   繁体   English

Spring Boot @Value 注解返回 null

[英]Spring Boot @Value annotaion return null

I'm trying to put api key in application.properties and get api key from it.我正在尝试将 api 密钥放在 application.properties 中并从中获取 api 密钥。

So I put api key in application.properties.所以我把 api 密钥放在 application.properties 中。

application.properties应用程序属性

server.port=8090

#My Key will be placed in here
shortweather.key=myapikey

And then I made a class to get api key from application.properties然后我做了一个类从 application.properties 获取 api 密钥

ApiKey.java class ApiKey.java 类

package com.wook.weather;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ApiKey {
    @Value("${shortweather.key}")
    private String apiKey;

    public String getApiKey() {
        return apiKey;
    }

    @Override
    public String toString() {
        return "ApiKey [apiKey=" + apiKey + "]";
    }
    
}

And I made an instance at main method and try to call getApiKey()我在 main 方法中创建了一个实例并尝试调用getApiKey()

Application.java应用程序.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;

@SpringBootApplication
public class Application {

    private final static String BASE_URL = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0";
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        
        String serviceKey = "apikey";
        String pageNo = "1";
        String numOfRows = "12";
        String dataType = "JSON";
        String base_date = "20211020";
        String base_time = "2300";
        String nx = "55";
        String ny = "127";

        DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL);
        factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);

        WebClient wc = WebClient.builder().uriBuilderFactory(factory).baseUrl(BASE_URL).build();

        String response = wc.get()
                .uri(uriBuilder -> uriBuilder.path("/getVilageFcst")
                        .queryParam("serviceKey", serviceKey)
                        .queryParam("numOfRows", numOfRows)
                        .queryParam("pageNo", pageNo)
                        .queryParam("dataType", dataType)
                        .queryParam("base_date", base_date)
                        .queryParam("base_time", base_time)
                        .queryParam("nx", nx)
                        .queryParam("ny", ny).build())
                .retrieve().bodyToMono(String.class).block();

        System.out.println(response);
        
        
        //I made ApiKey instance here
        ApiKey apk = new ApiKey();
        //This part return null
        System.out.println(apk.getApiKey());
    }
}

But I get null.但我得到空值。

I want to get value that is in application.properties.我想获得 application.properties 中的值。

How can I fix this issue?我该如何解决这个问题?

Spring only injects value while the bean is managed by spring. Spring 只在 bean 由 spring 管理时注入值。 You are creating an instance of the bean by calling new.您正在通过调用 new 创建 bean 的一个实例。 This is where you are taking control of yourself and spring is no longer able to inject value.这是你控制自己的地方,春天不再能够注入价值。 Rather you should do this:相反,您应该这样做:

@AutoWired
private ApiKey apk;

And also you marked the ApiKey class with @Component.你还用@Component 标记了 ApiKey 类。 So, spring will create an instance and then inject it to the main call by auto wiring.因此,spring 将创建一个实例,然后通过自动连接将其注入到主调用中。 And when spring takes control over instantiation, you will get your desired value.当 spring 控制实例化时,您将获得所需的值。

Complete code:完整代码:


    @SpringBootApplication
    public class Application implements CommandLineRunner {
    
        private final ApiKey apk;
    
        public Application( ApiKey apk ) {
            this.apk = apk;
        }
    
    
        public static void main( String[] args ) {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void run( String... args ) throws Exception {
            
            String serviceKey = "apikey";
            String pageNo = "1";
            String numOfRows = "12";
            String dataType = "JSON";
            String base_date = "20211020";
            String base_time = "2300";
            String nx = "55";
            String ny = "127";
    
            DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(BASE_URL);
            factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
    
            WebClient wc = WebClient.builder().uriBuilderFactory(factory).baseUrl(BASE_URL).build();
    
            String response = wc.get()
                    .uri(uriBuilder -> uriBuilder.path("/getVilageFcst")
                            .queryParam("serviceKey", serviceKey)
                            .queryParam("numOfRows", numOfRows)
                            .queryParam("pageNo", pageNo)
                            .queryParam("dataType", dataType)
                            .queryParam("base_date", base_date)
                            .queryParam("base_time", base_time)
                            .queryParam("nx", nx)
                            .queryParam("ny", ny).build())
                    .retrieve().bodyToMono(String.class).block();
    
            System.out.println(response);
            System.out.println(apk.getApiKey());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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