zoukankan      html  css  js  c++  java
  • 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.     

  • 相关阅读:
    抓取用户openid
    getaccesstoken方法
    https_request请求接口返回数据
    composer安装
    Linux下mysql数据库root无法登录的情况
    nginx安装
    shell脚本采用crontab定时备份数据库日志
    Python之元类详细解析
    Python面向对象之封装、property特性、绑定方法与非绑定方法
    Python之面向对象的组合、多态、菱形问题、子类中重用父类的两种方式
  • 原文地址:https://www.cnblogs.com/aknife/p/11905920.html
Copyright © 2011-2022 走看看