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

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

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

第一种方式

 

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

 

 

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

 

[html] view plain copy
 
  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.   
  6. @Component  
  7. public class Student {  
  8.   
  9.   
  10.   
  11.     @Autowired  
  12.     private Environment env;  
  13.   
  14.     public void speak() {  
  15.         System.out.println("=========>" + env.getProperty("aaa"));  
  16.   
  17.     }  
  18.   
  19. }  
  20.   
  21.    

 

 

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

 

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

posted @ 2019-11-21 15:23  ___mouM  阅读(5014)  评论(0编辑  收藏  举报