框架配置文件

 在这3种框架搭配使用的时候,我们往往需要写很多xml配置文件来配置各个框架的依赖关系。大的项目中,xml配置文件的过多,过于繁琐,导致查找起来会很不方便。

在这种情况下,我们需要简化我们的配置文件,同时结合部分xml来进行配置,这时候我们想到了annotation,这个近几年炒得很火的玩意。annotation和xml各自的好处和弊端我就不多说了,看代码吧。
开发环境要求: jdk6.0以上。tomcat5.5以上(也许tomcat5.0也行 不过没试过)
先从hibernate入手吧:
按照以往的写法,我们需要有.hbm文件来完成po映射。现在我们通过annotation省去了这部分工作。
具体代码如下:这是一个po类
Java代码
  1. import javax.persistence.Column;   
  2. import javax.persistence.Entity;   
  3. import javax.persistence.GeneratedValue;   
  4. import javax.persistence.Id;   
  5. import javax.persistence.Table;   
  6.   
  7. @Entity  
  8. @Table(name = "userlog")   
  9. public class UserLog {   
  10.     @Id  
  11.     @GeneratedValue  
  12.     private Long id;   
  13.   
  14.     @Column(name = "loginName")   
  15.     private String loginName;   
  16.   
  17. ....下面是setter/getter方法。  
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "userlog")
public class UserLog {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "loginName")
    private String loginName;

....下面是setter/getter方法。


我们没在spring配置文件中配置hibernate连接信息,还是采用传统的hibernate.cfg.xml,当然也可以在spring中配置。代码如下:
Java代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <!DOCTYPE hibernate-configuration PUBLIC   
  3.         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">   
  5. <hibernate-configuration>   
  6.     <session-factory>   
  7.         <property name="connection.datasource">java:/comp/env/jdbc/ExampleDB</property>   
  8.          
  9.         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>   
  10.            
  11.         <!--  <property name="hbm2ddl.auto">create</property>-->   
  12.         <property name="show_sql">true</property>   
  13.         <mapping class="com.nuctech.po.UserLog"/>   
  14.           
  15.     </session-factory>   
  16. </hibernate-configuration>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
	    <property name="connection.datasource">java:/comp/env/jdbc/ExampleDB</property>
	  
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		
		<!--  <property name="hbm2ddl.auto">create</property>-->
		<property name="show_sql">true</property>
        <mapping class="com.nuctech.po.UserLog"/>
       
    </session-factory>
</hibernate-configuration>


通过mapping class 我们就完成了po映射。

OK!我们再看dao层:

Java代码 @Component  
  1. public class TestDao{   
  2.  @Resource  
  3.     private SessionFactory sessionFactory;   
  4.   
  5.     public SessionFactory getSessionFactory() {   
  6.     return sessionFactory;   
  7.     }   
  8.   
  9.     public void setSessionFactory(SessionFactory sf) {   
  10.     this.sessionFactory = sf;   
  11.     }   
  12.    public Session getSession() {   
  13.         return sessionFactory.getCurrentSession();   
  14.     }   
  15.    public void save(Object obj){   
  16.     getSession().save(obj);   
  17.     }   
  18. }  
@Component
public class TestDao{
 @Resource
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
	return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sf) {
	this.sessionFactory = sf;
    }
   public Session getSession() {
        return sessionFactory.getCurrentSession();
    }
   public void save(Object obj){
	getSession().save(obj);
    }
}

在这里,我们的dao采用了@Component 表示它是一个组件,在别的类中将会去调用。
@Resource 引用SessionFactory 的bean.
关于annotation 可以参考Spring-Reference_zh_CN.chm

再来看我们的Action:
Java代码  
  1. @Component("TestAction")   
  2. public class TestAction extends ActionSupport {   
  3.    @Resource  
  4.     private TestDao dao; //这里引用上面的Component    
  5.     private UserLog log;   
  6.    ...setter/getter方法   
  7.   
  8.      其他的写法都一样了。   
  9.   
  10. }  
@Component("TestAction")
public class TestAction extends ActionSupport {
   @Resource
    private TestDao dao; //这里引用上面的Component 
    private UserLog log;
   ...setter/getter方法

     其他的写法都一样了。

}



再看我们的struts配置文件
Java代码
  1. <!DOCTYPE struts PUBLIC   
  2.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  3.         "http://struts.apache.org/dtds/struts-2.0.dtd">   
  4. <struts>   
  5.     <include file="struts-default.xml"/>   
  6.         <constant name="struts.objectFactory" value="spring" />   
  7.         <constant name="struts.devMode" value="true" />   
  8.      <package name="com.nuctech.action" extends="struts-default">   
  9.                  <action name="queryUserLogByPage" class="TestAction" method="queryUserLogByPage">   
  10.         ......省略....   
  11.          </action>   
  12.     </package>   
  13.        
  14. </struts>  
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml"/>
    	<constant name="struts.objectFactory" value="spring" />
		<constant name="struts.devMode" value="true" />
     <package name="com.nuctech.action" extends="struts-default">
                 <action name="queryUserLogByPage" class="TestAction" method="queryUserLogByPage">
        ......省略....
         </action>
    </package>
    
</struts>

注意这个action名字与@Component("TestAction")一致。
在没有annotation的情况下,我们在spring的配置文件中需要有很多的bean注入。现在都已经在类中注入了 那么我们现在来看spring配置文件:
Java代码
  1.   
  2. <?xml version="1.0" encoding="UTF-8"?>   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:jee="http://www.springframework.org/schema/jee"  
  8.     xsi:schemaLocation="   
  9.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  10.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd   
  11.     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd   
  12.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">   
  13.     <context:annotation-config />   
  14.   
  15.     <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>   
  16.        
  17.     <bean id="sessionFactory"  
  18.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">   
  19.         <property name="configLocation" value="classpath:/hibernate.cfg.xml" />   
  20.     </bean>   
  21.     <bean id="transactionManager"  
  22.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">   
  23.         <property name="sessionFactory" ref="sessionFactory" />   
  24.     </bean>   
  25.   
  26.     <context:component-scan base-package="com.xxxx"/>   
  27.     <tx:annotation-driven/>   
  28. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<context:annotation-config />

	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:/hibernate.cfg.xml" />
	</bean>
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<context:component-scan base-package="com.xxxx"/>
	<tx:annotation-driven/>
</beans>



我们只在这个配置文件中配置了sessionFactory.以前需要配置的bean不见了。
另外附上我们的jndi配置文件,在WebContent(WebRoot)下面的META-INF文件夹下面的context.xml。
Java代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <Context antiResourceLocking="false">   
  3.     <!-- 以下段配置session在tomcat重启时的持久化策略,saveOnRestart为false时不进行持久化,方便调试时使用 -->   
  4.     <Manager className="org.apache.catalina.session.PersistentManager"  
  5.         debug="0" saveOnRestart="false" maxActiveSessions="-1"  
  6.         minIdleSwap="-1" maxIdleSwap="-1" maxIdleBackup="-1">   
  7.         <Store className="org.apache.catalina.session.FileStore"  
  8.             directory="mydir" />   
  9.     </Manager>   
  10.     <!-- MySQL配置-->   
  11.         <Resource name="jdbc/ExampleDB" type="javax.sql.DataSource"  
  12.             driverClassName="com.mysql.jdbc.Driver"  
  13.             url="jdbc:mysql://localhost:3306/book?useUnicode=true&amp;characterEncoding=utf-8"  
  14.             username="root" password="123" validationQuery="select 1"  
  15.             maxIdle="4" maxWait="5000" maxActive="8" removeAbandoned="true"  
  16.             removeAbandonedTimeout="120">   
  17.         </Resource>   
  18.        
  19. </Context>  
<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="false">
	<!-- 以下段配置session在tomcat重启时的持久化策略,saveOnRestart为false时不进行持久化,方便调试时使用 -->
	<Manager className="org.apache.catalina.session.PersistentManager"
		debug="0" saveOnRestart="false" maxActiveSessions="-1"
		minIdleSwap="-1" maxIdleSwap="-1" maxIdleBackup="-1">
		<Store className="org.apache.catalina.session.FileStore"
			directory="mydir" />
	</Manager>
	<!-- MySQL配置-->
		<Resource name="jdbc/ExampleDB" type="javax.sql.DataSource"
			driverClassName="com.mysql.jdbc.Driver"
			url="jdbc:mysql://localhost:3306/book?useUnicode=true&amp;characterEncoding=utf-8"
			username="root" password="123" validationQuery="select 1"
			maxIdle="4" maxWait="5000" maxActive="8" removeAbandoned="true"
			removeAbandonedTimeout="120">
		</Resource>
	
</Context>

注意这个jndi名字与hibernate.cfg.xml中一致。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值