2026/1/19 7:14:36
网站建设
项目流程
长沙 建网站,网站建设建站流程方案,溜冰后做爰在线网站,新手做导航网站#x1f9d1; 博主简介#xff1a;CSDN博客专家#xff0c;历代文学网#xff08;PC端可以访问#xff1a;https://literature.sinhy.com/#/literature?__c1000#xff0c;移动端可微信小程序搜索“历代文学”#xff09;总架构师#xff0c;15年工作经验#xff0c;… 博主简介CSDN博客专家历代文学网PC端可以访问https://literature.sinhy.com/#/literature?__c1000移动端可微信小程序搜索“历代文学”总架构师15年工作经验精通Java编程高并发设计Springboot和微服务熟悉LinuxESXI虚拟化以及云原生Docker和K8s热衷于探索科技的边界并将理论知识转化为实际应用。保持对新技术的好奇心乐于分享所学希望通过我的实践经历和见解启发他人的创新思维。在这里我希望能与志同道合的朋友交流探讨共同进步一起在技术的世界里不断学习成长。技术合作请加本人wx注明来自csdnforeast_sea浅析Spring中的PropertySource 的基本使用一、PropertySource 简介org.springframework.context.annotation.PropertySource是一个注解可以标记在类上、接口上、枚举上在运行时起作用。而Repeatable(value PropertySources.class) 表示在PropertySources 中此注解时可以重复使用的。二、PropertySource与Environment读取配置文件 此注解PropertySource 为Spring 中的 Environment提供方便和声明机制通常与Configuration一起搭配使用。新建一个maven 项目添加pom.xml 依赖?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdcom.spring.propertysource/groupIdartifactIdspring-propertysource/artifactIdversion0.0.1-SNAPSHOT/versionnamespring-propertysource/namedescriptionDemo project for Spring Boot/descriptionpropertiesjava.version1.8/java.versionspring.version4.3.13.RELEASE/spring.version/propertiesdependenciesdependencygroupIdorg.springframework/groupIdartifactIdspring-core/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion${spring.version}/version/dependency/dependenciesbuildpluginManagementpluginsplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdversion3.2/versionconfigurationsource1.6/sourcetarget1.6/target/configuration/plugin/plugins/pluginManagement/build/project一般把版本名称统一定义在 标签中便于统一管理如上可以通过${…}来获取指定版本。定义一个application.properties 来写入如下配置com.spring.nameliuXuan com.spring.age18新建一个TestBean定义几个属性publicclassTestBean{privateStringname;privateIntegerage;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.namename;}publicIntegergetAge(){returnage;}publicvoidsetAge(Integerage){this.ageage;}OverridepublicStringtoString(){returnTestBean{namename\, ageage};}}新建一个main class 用来演示PropertySource 的使用ConfigurationPropertySource(valueclasspath:application.properties,ignoreResourceNotFoundfalse)publicclassSpringPropertysourceApplication{ResourceEnvironmentenvironment;BeanpublicTestBeantestBean(){TestBeantestBeannewTestBean();// 读取application.properties中的nametestBean.setName(environment.getProperty(com.spring.name));// 读取application.properties中的agetestBean.setAge(Integer.valueOf(environment.getProperty(com.spring.age)));System.out.println(testBean testBean);returntestBean;}publicstaticvoidmain(String[]args){ApplicationContextapplicationContextnewAnnotationConfigApplicationContext(SpringPropertysourceApplication.class);TestBeantestBean(TestBean)applicationContext.getBean(testBean);}}输出testBean TestBean{name‘liuXuan’, age18}Refreshing the spring contextConfiguration : 相当于 标签注意不是一个配置类可以有多个bean但是只能有一个PropertySource: 用于引入外部属性配置和Environment 配合一起使用。其中ignoreResourceNotFound 表示没有找到文件是否会报错默认为false就是会报错一般开发情况应该使用默认值设置为true相当于生吞异常增加排查问题的复杂性。引入PropertySource注入Environment然后就能用environment 获取配置文件中的value值。三、PropertySource与Value读取配置文件Value 基本使用 我们以DB的配置文件为例来看一下如何使用Value读取配置文件首先新建一个__DBConnection__具体代码如下// 组件beanComponentPropertySource(classpath:db.properties)publicclassDBConnection{Value(${DB_DRIVER_CLASS})privateStringdriverClass;Value(${DB_URL})privateStringdbUrl;Value(${DB_USERNAME})privateStringuserName;Value(${DB_PASSWORD})privateStringpassword;publicDBConnection(){}publicvoidprintDBConfigs(){System.out.println(Db Driver Class driverClass);System.out.println(Db url dbUrl);System.out.println(Db username userName);System.out.println(Db password password);}}类上加入Component 表示这是一个组件bean需要被spring进行管理PropertySource 用于获取类路径下的db.properties 配置文件Value用于获取properties中的key 对应的value值printDBConfigs方法打印出来对应的值。新建一个__db.properties__具体文件如下#MYSQL Database Configurations DB_DRIVER_CLASScom.mysql.jdbc.Driver DB_URLjdbc:mysql://localhost:3306/test DB_USERNAMEcxuan DB_PASSWORD111111 APP_NAMEPropertySourceExample这是一个MYSQL连接数据库驱动的配置文件。新建一个__SpringMainClass__用于测试DBConection中是否能够获取到Value的值publicclassSpringMainClass{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontextnewAnnotationConfigApplicationContext();// 注解扫描和ComponentScan 和 基于XML的配置context:component-scan base-package相同context.scan(com.spring.propertysource.app);// 刷新上下文环境context.refresh();System.out.println(Refreshing the spring context);// 获取DBConnection这个Bean调用其中的方法DBConnectiondbConnectioncontext.getBean(DBConnection.class);dbConnection.printDBConfigs();// 关闭容器(可以省略容器可以自动关闭)context.close();}}输出Refreshing the spring contextDb Driver Class com.mysql.jdbc.DriverDb url jdbc:mysql://localhost:3306/testDb username cxuanDb password 111111Value 高级用法 在实现了上述的例子之后我们再来看一下Value 的高级用法Value 可以直接为字段赋值例如:Value(cxuan)Stringname;Value(10)Integerage;Value(${APP_NAME_NOT_FOUND:Default})privateStringdefaultAppName;Value 可以直接获取系统属性例如Value(${java.home})// Value(#{systemProperties[java.home]}) SPEL 表达式StringjavaHome;Value(${HOME})Stringdir;Value 可以注解在方法和参数上Value(Test)// 可以直接使用Test 进行单元测试publicvoidprintValues(Strings,Value(another variable)Stringv){...}修改DBConnection后的代码如下publicclassDBConnection{Value(${DB_DRIVER_CLASS})privateStringdriverClass;Value(${DB_URL})privateStringdbUrl;Value(${DB_USERNAME})privateStringuserName;Value(${DB_PASSWORD})privateStringpassword;publicDBConnection(){}publicvoidprintDBConfigs(){System.out.println(Db Driver Class driverClass);System.out.println(Db url dbUrl);System.out.println(Db username userName);System.out.println(Db password password);}}在com.spring.propertysource.app 下 新增DBConfiguration作用是配置管理类管理DBConnection并读取配置文件代码如下ConfigurationPropertySources({PropertySource(classpath:db.properties),PropertySource(valueclasspath:root.properties,ignoreResourceNotFoundtrue)})publicclassDBConfiguration{Value(Default DBConfiguration)privateStringdefaultName;Value(true)privatebooleandefaultBoolean;Value(10)privateintdefaultInt;Value(${APP_NAME_NOT_FOUND:Default})privateStringdefaultAppName;Value(#{systemProperties[java.home]})// Value(${java.home})privateStringjavaHome;Value(${HOME})privateStringhomeDir;BeanpublicDBConnectiongetDBConnection(){DBConnectiondbConnectionnewDBConnection();returndbConnection;}Value(Test)// 开启测试publicvoidprintValues(Strings,Value(another variable)Stringv){System.out.println(Input Argument 1 s);System.out.println(Input Argument 2 v);System.out.println(Home Directory homeDir);System.out.println(Default Configuration Name defaultName);System.out.println(Default App Name defaultAppName);System.out.println(Java Home javaHome);System.out.println(Home dir homeDir);System.out.println(Boolean defaultBoolean);System.out.println(Int defaultInt);}}使用SpringMainClass进行测试测试结果如下Input Argument 1 TestInput Argument 2 another variableHome Directory /Users/mr.lDefault Configuration Name Default DBConfigurationDefault App Name DefaultJava Home /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/jreHome dir /Users/mr.lBoolean trueInt 10Refreshing the spring contextDb Driver Class com.mysql.jdbc.DriverDb url jdbc:mysql://localhost:3306/testDb username cxuanDb password 111111可以看到上述代码并没有显示调用printValues 方法默认是以单元测试的方式进行的。四、PropertySource 与 Import Import 可以用来导入 PropertySource 标注的类具体代码如下新建一个PropertySourceReadApplication类用于读取配置文件并测试具体代码如下// 导入BasicPropertyWithJavaConfig类Import(BasicPropertyWithJavaConfig.class)publicclassPropertySourceReadApplication{ResourceprivateEnvironmentenv;Value(${com.spring.name})privateStringname;Bean(context)publicPropertySourceReadApplicationcontextLoadInitialized(){// 用environment 读取配置文件System.out.println(env.getProperty(com.spring.age));// 用Value 读取配置文件System.out.println(name name);returnnull;}publicstaticvoidmain(String[]args){// AnnotationConnfigApplicationContext 内部会注册BeannewAnnotationConfigApplicationContext(PropertySourceReadApplication.class);}}新建一个BasicPropertyWithJavaConfig类用于配置类并加载配置文件ConfigurationPropertySource(valueclasspath:application.properties)publicclassBasicPropertyWithJavaConfig{publicBasicPropertyWithJavaConfig(){super();}}启动PropertySourceReadApplication console能够发现读取到配置文件中的value值18name cxuan