通过Spring Bean 注入static变量,来设计一套适合测试,开发,生产环境的配置项

本文介绍如何在Spring项目中实现开发、测试及生产环境的配置管理。通过Maven配置不同环境的.properties文件,并利用Spring Bean注入方式,实现配置项在各环境间的平滑切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(http://blog.youkuaiyun.com/initphp/article/details/8834844)


这边文章的目的主要是为了在spring开发web项目的时候,让我们的测试,开发,生产环境的配置项

  • .properties作为配置文件。

我们首先需要建立一个config文件夹,然后创建开发,测试,生产环境的.properties配置项文件。

例如,dev.properties文件为开发环境,pre.properties文件为生产环境。

dev.properties配置内容为:

[html]  view plain  copy
 print ?
  1. #test  
  2. test.username=initphp  


那么,我们这个.properties文件的配置,如何打入xml文件中呢?别急,其实很简单,我们需要修改pom.xml


  • 配置pom.xml

[html]  view plain  copy
 print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  4.   
  5.   
  6.   
  7.     <!-- pom详细参数配置 -->  
  8.     <modelVersion>4.0.0</modelVersion>  
  9.     <artifactId>xxxx.server</artifactId>  
  10.     <name>xxxx server</name>  
  11.     <packaging>war</packaging>  
  12.     <version>1.0.0</version>  
  13.   
  14.     <!-- 自定义的参数变量,使用 例如:${org.springframework-version} -->  
  15.     <properties>  
  16.         <java-version>1.6</java-version>  
  17.         <org.springframework-version>3.1.1.RELEASE</org.springframework-version>  
  18.         <org.aspectj-version>1.6.10</org.aspectj-version>  
  19.         <org.slf4j-version>1.6.6</org.slf4j-version>  
  20.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  21.     </properties>  
  22.   
  23.     <!-- 配置文件 -->  
  24.     <profiles>  
  25.         <profile>  
  26.             <id>dev</id>  
  27.             <properties>  
  28.                 <env>dev</env>  
  29.             </properties>  
  30.             <activation>  
  31.                 <activeByDefault>true</activeByDefault>  
  32.             </activation>  
  33.         </profile>  
  34.         <profile>  
  35.             <id>qa</id>  
  36.             <properties>  
  37.                 <env>qa</env>  
  38.             </properties>  
  39.         </profile>  
  40.         <profile>  
  41.             <id>pre</id>  
  42.             <properties>  
  43.                 <env>pre</env>  
  44.             </properties>  
  45.         </profile>  
  46.         <profile>  
  47.             <id>prod</id>  
  48.             <properties>  
  49.                 <env>prod</env>  
  50.             </properties>  
  51.         </profile>  
  52.     </profiles>  
  53.       
  54.     <!-- 依赖的包 -->  
  55.     <dependencies>  
  56.       
  57.           
  58.     </dependencies>  
  59.       
  60.     <!-- 编译设置 -->  
  61.     <build>  
  62.         <filters>  
  63.             <filter>config/${env}.properties</filter>  
  64.         </filters>  
  65.         <resources>  
  66.             <resource>  
  67.                 <directory>src/main/resources</directory>  
  68.                 <filtering>true</filtering>  
  69.             </resource>  
  70.         </resources>  
  71.   
  72.         <plugins>  
  73.             <plugin>  
  74.                 <artifactId>maven-eclipse-plugin</artifactId>  
  75.                 <version>2.9</version>  
  76.                 <configuration>  
  77.                     <additionalProjectnatures>  
  78.                         <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>  
  79.                     </additionalProjectnatures>  
  80.                     <additionalBuildcommands>  
  81.                         <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>  
  82.                     </additionalBuildcommands>  
  83.                     <downloadSources>true</downloadSources>  
  84.                     <downloadJavadocs>true</downloadJavadocs>  
  85.                 </configuration>  
  86.             </plugin>  
  87.             <plugin>  
  88.                 <groupId>org.apache.maven.plugins</groupId>  
  89.                 <artifactId>maven-compiler-plugin</artifactId>  
  90.                 <version>2.5.1</version>  
  91.                 <configuration>  
  92.                     <source>1.6</source>  
  93.                     <target>1.6</target>  
  94.                     <compilerArgument>-Xlint:all</compilerArgument>  
  95.                     <showWarnings>true</showWarnings>  
  96.                     <showDeprecation>true</showDeprecation>  
  97.                 </configuration>  
  98.             </plugin>  
  99.             <plugin>  
  100.                 <groupId>org.codehaus.mojo</groupId>  
  101.                 <artifactId>exec-maven-plugin</artifactId>  
  102.                 <version>1.2.1</version>  
  103.                 <configuration>  
  104.                     <mainClass>org.test.int1.Main</mainClass>  
  105.                 </configuration>  
  106.             </plugin>  
  107.         </plugins>  
  108.     </build>  
  109. </project>  

主要<profiles>中配置了各种环境的配置项参数。<filters>中,用于读取和替换配置。


  • 替换XML中的配置项变量,我们通过spring bean注入的方式,将配置项参数注入Config.java类中的静态变量。

例如我们主要注入到com.xxxx.xxxx.common.bo.ConfigBo,我们预先定义的一个配置类中。先看一下ConfigBo这个类:

[java]  view plain  copy
 print ?
  1. /** 
  2.  * 常量配置 
  3.  * @author hanqi 
  4.  */  
  5. public class ConfigBo {  
  6.   
  7.     /** 每页显示页数 */  
  8.     public static final int PAGE_SIZE              = 20;  
  9.       
  10.     public static String    USERNAME         = ""//被注入的static变量,不能有final终态关键字  
  11.   
  12.     //bean注入 USERNAME 必须要用 set函数  
  13.     public void setUserName(String userName) {  
  14.         USERNAME = userName;  
  15.     }  
  16.   
  17. }  

我们需要修改xml文件,添加注入的Bean:

[html]  view plain  copy
 print ?
  1. <bean class="com.xxxx.xxxx.common.bo.ConfigBo">  
  2.     <property name="userName" value="${test.username}" />  
  3. </bean>  

这个时候,我们就能在项目中,静态调用ConfigBo.USERNAME这个常量了,而不需要关心测试环境,开发环境以及正式环境的区别了。

xml中的${test.username}实际上是将properties配置文件中的选项值进行了替换,所以在mvn install后,target目录下,查看xml文件,就可以看到userName的值就是"initphp"


### Spring Cloud 应用启动失败的原因分析 当Spring Cloud应用程序因未解析的配置项`config.info`而启动失败时,通常涉及以下几个可能原因: #### 1. 配置中心连接异常 如果Spring Cloud Config Server未能成功加载远程仓库中的配置文件,则可能导致`config.info`无法被正确注入。这可能是由于网络问题、Git仓库地址错误或认证凭证失效引起的[^2]。 #### 2. 属性占位符未替换 在某些情况下,Spring Boot可能会尝试提前初始化Bean实例,在此之前依赖于尚未完成解析的属性值。这种行为会引发`Unresolved Placeholder Exception`,表明`${}`形式的占位符未被实际值替代[^3]。 #### 解决方案 以下是几种常见的解决方法: - **验证Config Server状态** 确认Config Server能够正常运行并访问到存储库内的资源。可以通过浏览器或者Postman工具直接请求服务端暴露出来的API接口来测试连通性和数据准确性[^4]。 - **调整引导顺序** 如果存在复杂的上下文初始化逻辑,可以考虑修改application.properties/yml设置,默认延迟部分组件的创建直到所有必要的环境变量都已就绪为止。例如启用懒加载模式: ```yaml spring: cloud: config: fail-fast: false # 设置为false允许即使缺少一些外部化配置也能继续执行程序流程 ``` - **提供默认值** 对那些可能出现缺失风险的关键参数设定合理的备选选项以防止单点故障影响整体功能实现。比如这样定义: ```properties config.info=${CONFIG_INFO_FROM_EXTERNAL_SOURCE:-default_value} ``` 以上措施有助于缓解由未知因素触发的应用崩溃状况,并增强系统的健壮性面对不可预见的情况作出适当反应[^5]。 ```java @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值