Spring的一些應用經驗(1)- -
1.單一的屬性檔案提供給使用者,來定義Spring內部會使用到的屬性。
在開發的過程中,我們往往會發現這麼一個情況:一套DataSource配置會出現在一個應用的好幾個設定檔中,當你改變了一個而忽略了其它兩個的時候,你的應用就會報錯,其中最為明顯的是Hibernate.properties中的datasource配置(xDoclet用來構建資料庫,Hibernate用來做直接的資料操作)和applicationContext.xml中Hibernate配置的相關部分。還好,Spring提供給了我們PropertyPlaceholderConfigurer類,能讓我們只關心與Hibernate.properties的配置,而applicationContext.xml中的相關配置可以直接讀取屬性檔案。
-------------------------------------------------------------------------------
<bean
id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${hibernate.connection.driver_class}</value>
</property>
<property name="url">
<value>${hibernate.connection.url}</value>
</property>
<property name="username">
<value>${hibernate.connection.username}</value>
</property>
<property name="password">
<value>${hibernate.connection.password}</value>
</property>
</bean>
<bean
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>hibernate.properties</value>
</property>
</bean>
-------------------------------------------------------------------------------
2.日誌的方便配置
一個應用有一個好的日誌系統是必須的,請注意Spring提供的兩個類,Log4jConfigServlet和Log4jConfigListener。它們都將被配置在Web應用的web.xml檔案中。
-------------------------------------------------------------------------------
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classess/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>log4jConfigServlet</servlet-name>
<servlet-class>org.springframework.web.util.Log4jConfigServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-------------------------------------------------------------------------------
3.Hibernate Lazy Load的Spring方法實現
Hibernate的lazy load對於開發應用的重要性,不言自明。我們現在來看一下如何在Spring控制的Hibernate Session中方便的使用lazy load。在這裡我們將用到Spring很好的基礎包org.springframework.beans。實際上很簡單,Hibernate的Object定義是POJO,而Spring提供的支援也是針對POJO的。一切看起來順理成章。
-------------------------------------------------------------------------------
public BasePeer loadWithLazy(BasePeer peer, String[] propertyNames) {
BeanWrapper beanWrapper = new BeanWrapperImpl(peer);
for (int i = 0; i < propertyNames.length; i++) {
try {
Hibernate.initialize(beanWrapper.getPropertyValue(propertyNames[i]));
}
catch (HibernateException e) {
log.error(e.getMessage());
}
}
return peer;
}
-------------------------------------------------------------------------------
public void testLoadGroup() {
SecurityGroupPeer group = groupDao.loadGroupByName("Administrator");
assertEquals("Administrator Description", group.getDescription());
SecurityGroupPeer group2 = groupDao.loadGroup(1, new String[] { "users"});
assertEquals(2, group2.getUsers().size());
}
-------------------------------------------------------------------------------