@Value в Springboot возвращает ноль - PullRequest
0 голосов
/ 26 ноября 2018

У меня есть application.properties, который находится в ресурсах

apllication.properties

hsm.provider=software
hsm.name=TestHsm
hsm.port=3001
hsm.ip=127.0.0.1
hsm.timeout=10000

и контроллер

@RestController
@RequestMapping("/hsm")
public class Controller {

  @Value("${hsm.ip}")
  private String ip;

  @Value("${hsm.port}")
  private String port;

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

  @Value("${hsm.timeout}")
  private String timeout;

  @Value("${hsm.provider}")
  private String provider;}
}

однако, когда я запускаю приложение, все переменные остаются NULL.Чего мне не хватает?

РЕДАКТИРОВАТЬ Это структура проекта из папки src

src
├───main
│   ├───java
│   │   └───com
│   │       └───xyz
│   │           └───hsmservice
│   │               └───hsm
│   │                   └───api
│   │                           Application.java
│   │                           Controller.java
│   │                           HSM.java
│   │
│   └───resources
│       │   application.properties
│       │
│       └───META-INF
│               plugin.xml
│
└───test
    ├───java
    │       LibraryTest.java
    │
    └───resources

РЕДАКТИРОВАНИЕ 2 Вот класс приложения

@SpringBootApplication
public class Application {  
    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
    }
}

Ответы [ 5 ]

0 голосов
/ 27 февраля 2019

Хорошо, я решил с верхним ответом этот Вопрос.Я помещаю переменные и @Values ​​в сигнатуру конструктора, а не как переменные класса.

0 голосов
/ 26 ноября 2018

Я добавил ваш код в загрузочный проект Spring, и он находится в рабочем состоянии.

Извлеките этот 53482633 репозиторий и следуйте инструкциям, чтобы его запустить и запустить.

Также сравните свой код с этим приложением, чтобы выяснить, что происходит с вашей стороны.

В случае, если у вас все еще есть какие-либо проблемы, пожалуйста, опубликуйте их здесь.

0 голосов
/ 26 ноября 2018

Судя по структуре вашего пакета, эти свойства обязательно должны быть загружены.Единственно возможный вариант - создать экземпляр класса Controller как new Controller() вместо того, чтобы пружина вводила класс (используя @Autowired или конструктор).

0 голосов
/ 26 ноября 2018

Controller.java

С Lombok

package com.example.demo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hsm")
@Data
public class Controller {
    @Value("${hsm.ip}")
    private String ip;

    @Value("${hsm.port}")
    private String port;

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

    @Value("${hsm.timeout}")
    private String timeout;

    @Value("${hsm.provider}")
    private String provider;
}

Без Lombok (генерируется Intelliji - Refactor DeLombok)

    package com.example.demo;

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    @RequestMapping("/hsm")
    public class Controller {
        @Value("${hsm.ip}")
        private String ip;

        @Value("${hsm.port}")
        private String port;

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

        @Value("${hsm.timeout}")
        private String timeout;

        @Value("${hsm.provider}")
        private String provider;

        public Controller() {
        }

        public String getIp() {
            return this.ip;
        }

        public String getPort() {
            return this.port;
        }

        public String getName() {
            return this.name;
        }

        public String getTimeout() {
            return this.timeout;
        }

        public String getProvider() {
            return this.provider;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public void setPort(String port) {
            this.port = port;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setTimeout(String timeout) {
            this.timeout = timeout;
        }

        public void setProvider(String provider) {
            this.provider = provider;
        }

        public boolean equals(final Object o) {
            if (o == this) return true;
            if (!(o instanceof Controller)) return false;
            final Controller other = (Controller) o;
            if (!other.canEqual((Object) this)) return false;
            final Object this$ip = this.getIp();
            final Object other$ip = other.getIp();
            if (this$ip == null ? other$ip != null : !this$ip.equals(other$ip)) return false;
            final Object this$port = this.getPort();
            final Object other$port = other.getPort();
            if (this$port == null ? other$port != null : !this$port.equals(other$port)) return false;
            final Object this$name = this.getName();
            final Object other$name = other.getName();
            if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
            final Object this$timeout = this.getTimeout();
            final Object other$timeout = other.getTimeout();
            if (this$timeout == null ? other$timeout != null : !this$timeout.equals(other$timeout)) return false;
            final Object this$provider = this.getProvider();
            final Object other$provider = other.getProvider();
            if (this$provider == null ? other$provider != null : !this$provider.equals(other$provider)) return false;
            return true;
        }

        protected boolean canEqual(final Object other) {
            return other instanceof Controller;
        }

        public int hashCode() {
            final int PRIME = 59;
            int result = 1;
            final Object $ip = this.getIp();
            result = result * PRIME + ($ip == null ? 43 : $ip.hashCode());
            final Object $port = this.getPort();
            result = result * PRIME + ($port == null ? 43 : $port.hashCode());
            final Object $name = this.getName();
            result = result * PRIME + ($name == null ? 43 : $name.hashCode());
            final Object $timeout = this.getTimeout();
            result = result * PRIME + ($timeout == null ? 43 : $timeout.hashCode());
            final Object $provider = this.getProvider();
            result = result * PRIME + ($provider == null ? 43 : $provider.hashCode());
            return result;
        }

        public String toString() {
            return "Controller(ip=" + this.getIp() + ", port=" + this.getPort() + ", name=" + this.getName() + ", timeout=" + this.getTimeout() + ", provider=" + this.getProvider() + ")";
        }
    }

DemoApplication.java

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {
    @Autowired
    Controller controller;

    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args)) {
            DemoApplication app = ctx.getBean(DemoApplication.class);
            app.run(args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run(String... args) throws Exception {
        System.out.println(controller);
    }
}

Выход: Controller(ip=127.0.0.1, port=3001, name=TestHsm, timeout=1000, provider=software)

0 голосов
/ 26 ноября 2018

У меня раньше была такая же проблема, и @Value не работал для контроллера, но работал для классов компонентов, поэтому я использовал приведенное ниже решение.

Вы можете @Autowire Environment environment, а затем environment.getProperty("hsm.provider").

Примечание. Это просто обходное решение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...