Home > Blockchain >  Spring : Cannot get value from application.properties
Spring : Cannot get value from application.properties

Time:12-15

I created Spring project via Spring Initializr with project following struct:

enter image description here

I defined property in application.properties file :

my.prop=testvalue

I inject this value into MyClass as following :

@Component
class MyClass {

    @Value("${my.prop}")
    private String myProp;

    public String getMyProp() {
        return myProp;
    }
}

ConfigBeans defined as following:

package com.example.propertiesdemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigBeans {
    @Bean
    public MyClass myLitoBean() {
        return new MyClass();
    }
}

PropertiesdemoApplication.java :

package com.example.propertiesdemo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class PropertiesdemoApplication {
    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(
                        ConfigBeans.class);
        MyClass myClass = context.getBean(MyClass.class);
        System.out.println(myClass.getMyProp());
    }
}

I am expecting that after executing line System.out.println(myClass.getMyProp()); will be printed value of myprop defined in application.properties (i.e testvalue), but after running (via Netbeans IDE) I get output :

${my.prop}

What was missed / wromg in this code ? Thanks in advance

CodePudding user response:

You are creating MyClass bean twice.

  1. Using @component annotation
  2. using @bean annotation in the config class (use method name lowerCamelCase i.e. in your case myClass())

Create bean only once using any one of the above.

CodePudding user response:

You dont need to create an application context in the main method like this. The presented code is a kind of mixture of "traditional" spring and spring boot. So you're kind of bypassing all the goodies that spring boot offers, among which is automatic application.properties loading.

If you're using spring boot (there is a @SpringBootApplication annotation) then it will create everything by itself.

Usually it should be something like this

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

CodePudding user response:

@SpringBootApplication
public class PropertiesdemoApplication {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(PropertiesdemoApplication.class, args);
        MyClass myClass = context.getBean(MyClass.class);
        System.out.println(myClass.getMyProp());
    }
}
  • Related