Spring Boot @Value Properties

后端 未结 8 1197
刺人心
刺人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 10:45

    I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.

    1. create a class like this:
        import org.springframework.boot.context.properties.ConfigurationProperties;
    
        @ConfigurationProperties(prefix = "file")
        public class FileProperties {
            private String directory;
    
            public String getDirectory() {
                return directory;
            }
    
            public void setDirectory(String dir) {
                this.directory = dir;
            }
        }
    
    
    1. add the following to your BootApplication class:
        @EnableConfigurationProperties({
            FileProperties.class
        })
    
    1. Inject FileProperties to your PrintProperty class, then you can get hold of the property through the getter method.

提交回复
热议问题