Давайте посмотрим на динамическое управление собственностью весной.
Используемые технологии:
  JDK 1.6.0_31 
  Весна 3.1.1 
  Кварц 1.8.5 
  Maven 3.0.2 
ШАГ 1: СОЗДАТЬ MAVEN ПРОЕКТ
Maven проект создается следующим образом. (Его можно создать с помощью Maven или IDE Plug-in).
ШАГ 2: БИБЛИОТЕКИ
Spring-зависимости добавляются в pom.xml Maven.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <properties> <spring.version>3.1.1.RELEASE</spring.version></properties><dependencies>    <!-- Spring 3 dependencies -->       <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-core</artifactId>  <version>${spring.version}</version> </dependency>      <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-context</artifactId>  <version>${spring.version}</version> </dependency> <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-context-support</artifactId>  <version>${spring.version}</version> </dependency>  <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-tx</artifactId>  <version>${spring.version}</version> </dependency> <!-- Quartz dependency -->  <dependency>     <groupId>org.quartz-scheduler</groupId>     <artifactId>quartz</artifactId>     <version>1.8.5</version> </dependency> <!-- Log4j dependency --> <dependency>  <groupId>log4j</groupId>  <artifactId>log4j</artifactId>  <version>1.2.16</version> </dependency></dependencies> | 
ШАГ 3: СОЗДАЙТЕ DynamicPropertiesFile.properties
DynamicPropertiesFile охватывает динамические свойства приложения.
| 01 02 03 04 05 06 07 08 09 10 11 | # This property defines message content# Possible values = Text. Default value : WelcomeMessage_Content = Welcome Visitor# This property defines minimum visitor count# Possible values = positive integer. Default value : 1Minimum_Visitor_Count = 1# This property defines maximum visitor count# Possible values = positive integer. Default value : 10Maximum_Visitor_Count = 10 | 
ШАГ 4: СОЗДАТЬ applicationContext.xml
Контекст приложения создается следующим образом:
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |     xsi:schemaLocation="http://www.springframework.org/schema/beans <!-- Beans Declaration --> <!-- Core Dynamic Properties Bean Declaration --> <beanid="CoreDynamicPropertiesBean"class="org.springframework.beans.factory.config.PropertiesFactoryBean"scope="prototype">  <propertyname="location"value="classpath:DynamicPropertiesFile.properties"/>   </bean> <!-- Dynamic Properties Map Declaration --> <beanid="DynamicPropertiesMap"class="java.util.HashMap"/> <!-- Dynamic Properties File Reader Task Declaration --> <beanid="DynamicPropertiesFileReaderTask"class="com.otv.dynamic.properties.task.DynamicPropertiesFileReaderTask">  <propertyname="dynamicPropertiesMap"ref="DynamicPropertiesMap"/> </bean> <!-- End of Beans Declaration --> <!-- Scheduler Configuration --> <!-- Job Detail--> <beanid="DynamicPropertiesFileReaderTaskJobDetail"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  <propertyname="targetObject"ref="DynamicPropertiesFileReaderTask"/>  <propertyname="targetMethod"value="start"/> </bean> <!-- Simple Trigger --> <beanid="DynamicPropertiesFileReaderTaskTrigger"class="org.springframework.scheduling.quartz.SimpleTriggerBean">  <propertyname="jobDetail"ref="DynamicPropertiesFileReaderTaskJobDetail"/>  <propertyname="repeatInterval"value="60000"/>  <propertyname="startDelay"value="0"/> </bean> <beanclass="org.springframework.scheduling.quartz.SchedulerFactoryBean">  <propertyname="jobDetails">     <list>        <refbean="DynamicPropertiesFileReaderTaskJobDetail"/>     </list>  </property>  <propertyname="triggers">     <list>     <refbean="DynamicPropertiesFileReaderTaskTrigger"/>     </list>  </property> </bean> <!-- End of Scheduler Configuration --></beans> | 
ШАГ 5: СОЗДАЙТЕ SystemConstants CLASS
Новый класс SystemConstants создан. Этот класс охватывает все системные константы.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | packagecom.otv.common;/** * System Constants * * @author  onlinetechvision.com * @since   26 May 2012 * @version 1.0.0 * */publicclassSystemConstants { //Names of Dynamic Properties... publicstaticfinalString DYNAMIC_PROPERTY_MESSAGE_CONTENT = "Message_Content"; publicstaticfinalString DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT = "Minimum_Visitor_Count"; publicstaticfinalString DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT = "Maximum_Visitor_Count"; //Default Values of Dynamic Properties... publicstaticfinalString DYNAMIC_PROPERTY_MESSAGE_CONTENT_DEFAULT_VALUE       = "Welcome"; publicstaticfinalString DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT_DEFAULT_VALUE = "1"; publicstaticfinalString DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT_DEFAULT_VALUE = "10"; publicstaticfinalString BEAN_NAME_CORE_DYNAMIC_PROPERTIES_BEAN = "CoreDynamicPropertiesBean"; publicstaticfinalString APPLICATION_CONTEXT_FILE_NAME = "applicationContext.xml";} | 
ШАГ 6: СОЗДАЙТЕ DynamicPropertiesFileReaderTask CLASS
Класс DynamicPropertiesFileReaderTask создан. Этим классом управляет Кварц. Он читает все динамические свойства через DynamicPropertiesFile , вызывая метод «start» каждую минуту. Период чтения можно изменить через applicationContext.xml .
Обратите внимание, что областью действия coreDynamicPropertiesBean является Singleton по умолчанию. Он должен возвращать новые значения динамических свойств во время выполнения, поэтому его область должна быть установлена Prototype . В противном случае новые значения не могут быть получены.
| 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | packagecom.otv.dynamic.properties.task;importjava.util.HashMap;importjava.util.Properties;importorg.apache.log4j.Logger;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.BeanFactory;importorg.springframework.beans.factory.BeanFactoryAware;importcom.otv.common.SystemConstants;/** * Dynamic Properties File Reader Task * * @author  onlinetechvision.com * @since   26 May 2012 * @version 1.0.0 * */publicclassDynamicPropertiesFileReaderTask implementsBeanFactoryAware { privatestaticLogger logger = Logger.getLogger(DynamicPropertiesFileReaderTask.class); privateProperties coreDynamicPropertiesBean; privateHashMap<String, String> dynamicPropertiesMap; privateBeanFactory beanFactory; /**  * Starts reading the dynamic properties  *  */ publicvoidstart() {  setCoreDynamicPropertiesBean(createCoreDynamicPropertiesBeanInstance());  logger.info("**** Dynamic Properties File Reader Task is being started... ****");  readConfiguration();  logger.info("**** Dynamic Properties File Reader Task is stopped... ****"); } /**  * Reads all the dynamic properties  *  */ privatevoidreadConfiguration() {  readMessageContent();  readMinimumVisitorCount();  readMaximumVisitorCount(); } /**  * Reads Message_Content dynamic property  *  */ privatevoidreadMessageContent() {  String messageContent = getCoreDynamicPropertiesBean()                       .getProperty(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT,           SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT_DEFAULT_VALUE);  if(messageContent.equals("")){         getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT,                  SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT_DEFAULT_VALUE);         logger.error(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT +                 " value is not found so its default value is set. Default value : "+                  SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT_DEFAULT_VALUE);        } else{         messageContent = messageContent.trim();         getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT, messageContent);         logger.info(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT + " : "+                getDynamicPropertiesMap().get(SystemConstants.DYNAMIC_PROPERTY_MESSAGE_CONTENT));        } } /**  * Reads Minimum_Visitor_Count dynamic property  *  */ privatevoidreadMinimumVisitorCount() {  String minimumVisitorCount = getCoreDynamicPropertiesBean()                                 .getProperty(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT,                         SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT_DEFAULT_VALUE).trim();  try{   if(Integer.parseInt(minimumVisitorCount) > 0){    getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT,                                              minimumVisitorCount);    logger.info(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT + " : "+           getDynamicPropertiesMap().get(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT));   } else{    getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT,                                        SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT_DEFAULT_VALUE);    logger.error("Invalid "+SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT +           " value encountered. Must be greater than 0. Its defaultvalue is set.                                  Default value : "+ SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT_DEFAULT_VALUE);   }  } catch(NumberFormatException nfe) {   logger.error("Invalid "+SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT +                  " value encountered. Must be numeric!", nfe);   logger.warn(SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT +                  " default value is set. Default value : "+                  SystemConstants.DYNAMIC_PROPERTY_MINIMUM_VISITOR_COUNT_DEFAULT_VALUE);  } } /**  * Reads Maximum_Visitor_Count dynamic property  *  */ privatevoidreadMaximumVisitorCount() {  String maximumVisitorCount = getCoreDynamicPropertiesBean()                                  .getProperty(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT,                                            SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT_DEFAULT_VALUE).trim();  try{   if(Integer.parseInt(maximumVisitorCount) > 0){    getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT, maximumVisitorCount);    logger.info(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT + " : "+                 getDynamicPropertiesMap()                        .get(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT));   } else{    getDynamicPropertiesMap().put(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT,                                  SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT_DEFAULT_VALUE);    logger.error("Invalid "+SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT +                " value encountered. Must be greater than 0. Its default value is set. Default value : "+                SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT_DEFAULT_VALUE);   }  } catch(NumberFormatException nfe) {   logger.error("Invalid "+SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT +                 " value encountered. Must be numeric!", nfe);   logger.warn(SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT +                  " default value is set. Default value : "+                  SystemConstants.DYNAMIC_PROPERTY_MAXIMUM_VISITOR_COUNT_DEFAULT_VALUE);  } } /**  * Gets CoreDynamicPropertiesBean  *  * @return Properties coreDynamicPropertiesBean  */ publicProperties getCoreDynamicPropertiesBean() {  returncoreDynamicPropertiesBean; } /**  * Sets CoreDynamicPropertiesBean  *  * @param Properties coreDynamicPropertiesBean  */ publicvoidsetCoreDynamicPropertiesBean(Properties coreDynamicPropertiesBean) {  this.coreDynamicPropertiesBean = coreDynamicPropertiesBean; } /**  * Gets DynamicPropertiesMap  *  * @return HashMap dynamicPropertiesMap  */ publicHashMap<String, String> getDynamicPropertiesMap() {  returndynamicPropertiesMap; } /**  * Sets DynamicPropertiesMap  *  * @param HashMap dynamicPropertiesMap  */ publicvoidsetDynamicPropertiesMap(HashMap<String, String> dynamicPropertiesMap) {  this.dynamicPropertiesMap = dynamicPropertiesMap; } /**  * Gets a new instance of CoreDynamicPropertiesBean  *  * @return Properties CoreDynamicPropertiesBean  */ publicProperties createCoreDynamicPropertiesBeanInstance() {  return(Properties) this.beanFactory.getBean(SystemConstants.BEAN_NAME_CORE_DYNAMIC_PROPERTIES_BEAN); } /**  * Sets BeanFactory  *  * @param BeanFactory beanFactory  */ publicvoidsetBeanFactory(BeanFactory beanFactory) throwsBeansException {  this.beanFactory = beanFactory; }} | 
ШАГ 7: СОЗДАТЬ КЛАСС ПРИЛОЖЕНИЙ
Приложение Class запускает проект.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | packagecom.otv.starter;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.otv.common.SystemConstants;/** * Application Starter Class * * @author  onlinetechvision.com * @since   26 May 2012 * @version 1.0.0 * */publicclassApplication { /**  * Main method of the Application  *  */ publicstaticvoidmain(String[] args) {  newClassPathXmlApplicationContext(SystemConstants.APPLICATION_CONTEXT_FILE_NAME); }} | 
ШАГ 8: ЗАПУСК ПРОЕКТА
Если класс приложения запущен, отображаются следующие журналы консоли:
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | 26.05.2012 17:25:09  INFO (DefaultLifecycleProcessor.java:334) - Starting beans inphase 214748364726.05.2012 17:25:09  INFO (SchedulerFactoryBean.java:648) - Starting Quartz Scheduler now26.05.2012 17:25:09  INFO (PropertiesLoaderSupport.java:177) - Loading properties filefrom class path resource [DynamicPropertiesFile.properties]26.05.2012 17:25:09  INFO (DynamicPropertiesFileReaderTask.java:36) - **** Dynamic Properties File Reader Task is being started... ****26.05.2012 17:25:09  INFO (DynamicPropertiesFileReaderTask.java:63) - Message_Content : Welcome Visitor26.05.2012 17:25:09  INFO (DynamicPropertiesFileReaderTask.java:76) - Minimum_Visitor_Count : 126.05.2012 17:25:09  INFO (DynamicPropertiesFileReaderTask.java:96) - Maximum_Visitor_Count : 1026.05.2012 17:25:09  INFO (DynamicPropertiesFileReaderTask.java:38) - **** Dynamic Properties File Reader Task is stopped... ****26.05.2012 17:26:09  INFO (PropertiesLoaderSupport.java:177) - Loading properties filefrom class path resource [DynamicPropertiesFile.properties]26.05.2012 17:26:09  INFO (DynamicPropertiesFileReaderTask.java:36) - **** Dynamic Properties File Reader Task is being started... ****26.05.2012 17:26:09  INFO (DynamicPropertiesFileReaderTask.java:63) - Message_Content : Welcome Visitor, Bruce!26.05.2012 17:26:09  INFO (DynamicPropertiesFileReaderTask.java:76) - Minimum_Visitor_Count : 226.05.2012 17:26:09  INFO (DynamicPropertiesFileReaderTask.java:96) - Maximum_Visitor_Count : 2026.05.2012 17:26:09  INFO (DynamicPropertiesFileReaderTask.java:38) - **** Dynamic Properties File Reader Task is stopped... **** | 
ШАГ 9: СКАЧАТЬ
OTV_SpringDynamicPropertyManagement
РЕКОМЕНДАЦИИ :
Spring Framework Reference 3.x
Ссылка: Dynamic Property Management весной от нашего партнера JCG Эрен Авсарогуллари в блоге Online Technology Vision .
