Spring Boot @Value Properties

后端 未结 8 1182
刺人心
刺人心 2020-12-10 10:05

I have a Spring Boot application and in one of the classes, I try to reference a property from the application.properties file using @Value. But, the property d

8条回答
  •  爱一瞬间的悲伤
    2020-12-10 10:44

    You haven't included package declarations in the OP but it is possible that neither @SpringBootApplication nor @ComponentScan are scanning for your @Component.

    The @ComponentScan Javadoc states:

    Either basePackageClasses or basePackages (or its alias value) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

    ISTR wasting a lot of time on this before and found it easiest to simply move my application class to the highest package in my app's package tree.

    More recently I encountered a gotcha were the property was being read before the value insertion had been done. Jesse's answer helped as @PostConstruct seems to be the earliest you can read the inserted values, and of course you should let Spring call this.

提交回复
热议问题