SpringBoot获得application.properties中数据的几种方式

时间:2023-03-09 23:00:29
SpringBoot获得application.properties中数据的几种方式

转:https://blog.csdn.net/qq_27298687/article/details/79033102

SpringBoot获得application.properties中数据的几种方式

SpringBoot获得application.properties中数据的几种方式

第一种方式

  1. @SpringBootApplication
  2. public class SpringBoot01Application {
  3. public static void main(String[] args) {
  4. ConfigurableApplicationContext  context=SpringApplication.run(SpringBoot01Application.class, args);
  5. <span style="color:#FF0000;">String str1=context.getEnvironment().getProperty("aaa");</span>
  6. System.out.println(str1);
  7. }
  8. }

第二种方式(自动装配到Bean中)

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.core.env.Environment;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class Student {
  7. @Autowired
  8. private Environment env;
  9. public void speak() {
  10. System.out.println("=========>" + env.getProperty("aaa"));
  11. }
  12. }

第三种方式(使用@value注解)

SpringBoot获得application.properties中数据的几种方式

    1. package com.example.demo.entity;
    2. import org.springframework.beans.factory.annotation.Value;
    3. import org.springframework.context.annotation.PropertySource;
    4. import org.springframework.stereotype.Component;
    5. @Component
    6. @PropertySource("classpath:jdbc.properties")//如果是application.properties,就不用写@PropertySource("application.properties"),其他名字用些
    7. public class Jdbc {
    8. @Value("${jdbc.user}")
    9. private String user;
    10. @Value("${jdbc.password}")
    11. private String password;
    12. public void speack(){
    13. System.out.println("username:"+user+"------"+"password:"+password);
    14. }
    15. }