How to read data from java properties file using Spring Boot

前端 未结 4 1427
青春惊慌失措
青春惊慌失措 2020-12-01 07:30

I have a spring boot application and I want to read some variable from my application.properties file. In fact below codes do that. But I think there is a good

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 08:23

    We can read properties file in spring boot using 3 way

    1. Read value from application.properties Using @Value

    map key as

    public class EmailService {
    
     @Value("${email.username}")
     private String username;
    

    }

    2. Read value from application.properties Using @ConfigurationProperties

    In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

      @Component
       @ConfigurationProperties("email")
        public class EmailConfig {
    
            private String   username;
        }
    

    3. Read application.properties Using using Environment object

    public class EmailController {

    @Autowired
    private Environment env;
    
    @GetMapping("/sendmail")
    public void sendMail(){     
        System.out.println("reading value from application properties file  using Environment ");
        System.out.println("username ="+ env.getProperty("email.username"));
        System.out.println("pwd ="+ env.getProperty("email.pwd"));
    }
    

    Reference : how to read value from application.properties in spring boot

提交回复
热议问题