• 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.     

  • 相关阅读:
    vue app项目 第一天 基本架构和路由配置
    uni-app真机调试报错request:fail abort解决方法
    C#中的虚函数virtual
    ASP.NET Core中返回 json 数据首字母大小写问题
    ASP.NET Core中使用Cache缓存
    ASP.NET Core WebApi使用ActionFilterAttribute过滤器
    ASP.NET Core WebApi使用JWT认证
    微信小程序自动识别收货地址
    开发常用网站
    微信小程序自定义导航栏组件
  • 原文地址:https://www.cnblogs.com/aknife/p/11905920.html
Copyright © 2020-2023  润新知