Amine Hatim
Amine Hatim

Reputation: 247

I can't get value of a property in spring-boot application

I am coding in spring-boot. I tried to get the value of properties.properties in other packages without success. For example in the classe ClassUtils.java, the value of testValue is always null

This is my project

enter image description here

This is my code:

package com.plugins.controller;

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

import com.plugins.domain.ClassUtils;

@RestController
public class SearchContactController {
    @Value("${environnement.test}")
    String testValue;

    @Value("${environnement.url}")
    String urlValue;

    @RequestMapping(value = "/test")
    public String pingRequest() {
        System.out.println("value ===> " + testValue + " /// " + urlValue);

        return "test !" + ClassUtils.getTestValue(); 
    }

}

This is my second class, where I can't get the value of testValue variable:

package com.plugins.domain;

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

@Component
public class ClassUtils {

    @Value("${environnement.test}")
    static String testValue;


    public static String getTestValue(){
        return "The return "+testValue;    
    }
}

This is my springApp.java

package com.plugins;

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

@SpringBootApplication
public class SpringBootVideApplication {

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

Upvotes: 2

Views: 5512

Answers (2)

Amine Hatim
Amine Hatim

Reputation: 247

I resolve this issue by addin @Autowired in the class which use the method of the other class this is a snippet

 // Class: SearchContactController.java  
@Autowired
    ClassUtils cd;

    @RequestMapping(value = "/ping")
    public String pingRequest() {
        return "Ping OK !" + cd.getTestValue();
    }

Upvotes: 1

kuhajeyan
kuhajeyan

Reputation: 11077

Enable @ComponentScan({"com.plugins"}) , in Application

To access the properties defined in application.properties

myapp.url="xxxxxx"

in your class

@Value("${myapp.url}")
private   String testValue;

but this cannot be a static variable, if it is a static variable you do some hack like this, by defining setter method

private static String testValue;

@Value("${myapp.url}")
public void testValue(String value) {
            testValue = value;
}

Upvotes: 2

Related Questions