ITeye博客

用annotation来配置spring2.5+hibernate3.2+struts2

pipe · 2008-12-11 13:20 · spring · Markdown

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

在这种情况下,我们需要简化我们的配置文件,同时结合部分xml来进行配置,这时候我们想到了annotation,这个近几年炒得很火的玩意。annotation和xml各自的好处和弊端我就不多说了,看代码吧。 开发环境要求:jdk6.0以上。tomcat5.5以上(也许tomcat5.0也行 不过没试过) 先从hibernate入手吧: 按照以往的写法,我们需要有.hbm文件来完成po映射。现在我们通过annotation省去了这部分工作。 具体代码如下:这是一个po类


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中配置。代码如下:


<?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层:


@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:


@Component("TestAction")
public class TestAction extends ActionSupport {
   @Resource
    private TestDao dao; //这里引用上面的Component 
    private UserLog log;
   ...setter/getter方法

     其他的写法都一样了。

}


再看我们的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配置文件:



<?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。


<?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中一致。

先就这样吧。

评论(3)

  1. #3 楼 · songfantasy · 2010-07-15 22:32

    @Component不建议使用,建议使用@service @controler等

  2. #2 楼 · pipe · 2008-12-15 14:30

    joeyhacker writes:

    不错,annotation确实很简洁,但是我觉得xml更大众化,毕竟它很流行。

    所以需要annotation与xml两者结合,xml用做struts2配置文件,其他地方可以用annotation,效果我感觉还是不错的。

  3. #1 楼 · joeyhacker · 2008-12-15 10:24

    不错,annotation确实很简洁,但是我觉得xml更大众化,毕竟它很流行。

评论功能维护中,当前仅展示历史评论。