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

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,就不用写@PropertyScource("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.     
  21. }  
  22.     
  23.     
  24.     
  25.     
  26.     

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值