0


springboot中获取配置文件中属性值的几种方式

目录

友情提醒:

先看文章目录,大致了解文章知识点结构,点击文章目录可直接跳转到文章指定位置。有用记得关注

第一章、使用@Value注解

①@Value注解用于获取配置文件中的属性定义并绑定到Java Bean或属性中。在核心配置文件applicatin.properties中,添加两个自定义配置项school.name和school.website。
在这里插入图片描述

②在SpringBootController中定义属性,并使用@Value注解或者自定义配置值,并对其方法进行测试

packagecom.example.springboot.web;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.ResponseBody;@ControllerpublicclassSpringBootController{@Value("${school.name}")privateString schoolName;@Value("${school.websit}")privateString schoolWebsit;@RequestMapping(value ="/springBoot/first")@ResponseBodypublicStringsay(){return schoolName +"------"+ schoolWebsit;}}

③访问浏览器成功,说明成功通过@value读取配置的属性值
在这里插入图片描述

第二章、使用@PropertySource注解

2.1)指定文件路径,在setter方法上添加@Value注解

@PropertySource(“classpath:coremail.properties”)是指定配置文件位置的注解。Spring 可以在类路径下找到并加载这个coremail.properties属性文件。需要再在属性上面搭配@value注解使用其中定义的属性值。
在这里插入图片描述

2.2)指定文件路径,在属性上添加@Value注解

在这里插入图片描述

2.3)使用ApplicationContextAware接口来获得TConfig中对应properties文件的属性值

2.3.1)TaskConfig类与TestTaskConfig类

有两个配置文件,使用两个config类指定properties类文件路径
在这里插入图片描述

@Configuration//当一个类被标注了@Configuration注解时,Spring会将这个类识别为配置类,// 用于定义Bean的创建和配置。即使没有显式地定义Bean,配置类本身也可以被注入到其他类中@PropertySource(value ={"classpath:mailSendConfig.properties"},encoding="utf-8")publicclassTaskConfig{}
@Configuration@PropertySource(value ={"classpath:testConfig.properties"},encoding="utf-8")publicclassTestTaskConfig{}

在这里插入图片描述

2.3.2)ConfigLoder类

用来加载config类

@ComponentpublicclassConfigLoder{@AutowiredstaticTaskConfig taskConfig;@AutowiredstaticTestTaskConfig testTaskConfig;publicstaticTaskConfiggetTaskConfig(){return taskConfig;}publicstaticTestTaskConfiggetTestTaskConfig(){return testTaskConfig;}}

在这里插入图片描述

2.3.3)启动类:启动只运行一次

//@SpringBootApplicationpublicclassLineApplicationimplementsApplicationRunner{@Overridepublicvoidrun(ApplicationArguments args)throwsException{System.out.println("====================");XXXXService mailSend =newXXXXService();
        mailSend.run();}publicstaticvoidmain(String[] args){SpringApplication.run(LineApplication.class,args);}}

2.3.4)springUtil类实现ApplicationContextAware接口

通过实现ApplicationContextAware接口获取ApplicationContext对象,来获得TaskConfig中对应properties文件的属性值。

@ComponentpublicclassSpringUtilimplementsApplicationContextAware{privatestaticApplicationContext applicationContext =null;@OverridepublicvoidsetApplicationContext(ApplicationContext applicationContext)throwsBeansException{if(SpringUtil.applicationContext ==null){SpringUtil.applicationContext = applicationContext;}}publicstaticApplicationContextgetApplicationContext(){return applicationContext;}publicstaticObjectgetBean(String name){returngetApplicationContext().getBean(name);}publicstatic<T>TgetBean(Class<T> clazz){returngetApplicationContext().getBean(clazz);}publicstatic<T>TgetBean(String name,Class<T> clazz){returngetApplicationContext().getBean(name, clazz);}publicstaticStringgetProperty(String propertyName){returngetApplicationContext().getEnvironment().getProperty(propertyName);}publicstaticStringgetProperty(Class clazz,StringPropertyName){AnnotationConfigApplicationContext context =newAnnotationConfigApplicationContext(clazz);ConfigurableEnvironment configurableEnvironment = context.getEnvironment();return configurableEnvironment.getProperty(PropertyName);}}

2.3.5)TestGetProperties测试类:测试获取属性值

packagecom.icbc.app.runner;importcom.icbc.app.config.SpringUtil;importcom.icbc.app.config.TaskConfig;importcom.icbc.app.config.TestTaskConfig;importorg.springframework.stereotype.Component;importjava.util.ResourceBundle;@ComponentpublicclassTestGetProperties{publicvoidrun(String... args)throwsException{//第一种:获取系统环境的   systemTime   值System.out.println("系统值systemTime="+System.getenv("CALLTIME"));//第二种:ResourceBundle获取testConfig配置文件的的  name 值ResourceBundle bundle =ResourceBundle.getBundle("testConfig");String name = bundle.getString("name");System.out.println("ResourceBundle获取name值="+ name);//第三种:TaskConfig.properties的sleepTime值String sleepTime =SpringUtil.getProperty(TaskConfig.class,"sleepTime");System.out.println("TaskConfig.properties的sleepTime值="+sleepTime);//第四种:TestTaskConfig.properties文件的Time值String time =SpringUtil.getProperty(TestTaskConfig.class,"Time");System.out.println("TestTaskConfig.properties文件的Time值="+time);}}

第三章、使用@Configurationproperties注解

@Configurationproperties(prefix=”xxx”)prefix的作用是区分同名配置,如果不指定,那么会去配置文件中寻找与该类的属性名一致的配置文件。
prefix怎么使用呢?
在生产环境配置文件applicatin-product.properties中,有自定义的三个school前缀的配置项
在这里插入图片描述

在核心配置文件applicatin.properties中激活生产环境,这里的product对应文件名application-produc的横杠后面的produc
在这里插入图片描述
当指定prefix之后,就不需要再在属性上面搭配@value注解使用,因为当指定前缀school之后,属性就会自动注入
在这里插入图片描述

第四章、使用Java Properties类

Properties prop =newProperties();try(InputStream input =newFileInputStream("config.properties")){
    prop.load(input);String dbUrl = prop.getProperty("db.url");String dbUser = prop.getProperty("db.user");String dbPassword = prop.getProperty("db.password");// 使用读取到的属性进行后续操作}catch(IOException ex){
    ex.printStackTrace();}

第五章、使用Environment接口

配置文件如图:
在这里插入图片描述

获取配置文件中的属性值:

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.core.env.Environment;importorg.springframework.stereotype.Component;@ComponentpublicclassMyComponent{publicstaticStringValue1;publicstaticStringValue2;@AutowiredprivateEnvironment environment;publicvoidgetPropertyFromEnvironment(){Value1= environment.getProperty("school.name");Value2= environment.getProperty("school.buile.age");System.out.println("Value1: "+Value+"Value1: "+Value2);}}

第六章、使用ResourceBundle类

新建一个配置文件:ResourceBunTest.properties,信息如下图
在这里插入图片描述
使用ResourceBundle类获取配置文件内容

publicclassResourceBundleTest{publicstaticvoidmain(String[] args){testResoBund();}//获取配置文件信息的方法publicstaticvoidtestResoBund(){//根据配置文件名称获得ResourceBundle  对象ResourceBundle bundle =ResourceBundle.getBundle("ResourceBunTest");String userId = bundle.getString("userId");String userName = bundle.getString("userName");String age = bundle.getString("age");System.out.println(userId+"---"+userName+"---"+age);}}

测试结果:获取成功
在这里插入图片描述

标签: spring boot java 后端

本文转载自: https://blog.csdn.net/baomingshu/article/details/135927528
版权归原作者 Holy_Java 所有, 如有侵权,请联系我们删除。

“springboot中获取配置文件中属性值的几种方式”的评论:

还没有评论