就给个实例,记录下。慢慢理解,有写的不好的地方需要提高。先理解思想就好~

bean.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 启动注解 -->
	<context:annotation-config/>
	
	<!-- 定义数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
	    <property name="url" value="jdbc:mysql://localhost:3306/weboutlook?useUnicode=true&amp;characterEncoding=UTF-8"/>
	    <property name="username" value="root"/>
	    <property name="password" value=""/>
	    <!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="1"/>
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="500"/>
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="2"/>
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="1"/>
	</bean>
	
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mappingResources">
			<list>
				<value>cn/kinca/weboutlook/beans/User.hbm.xml</value>
				<value>cn/kinca/weboutlook/beans/Email.hbm.xml</value>
				<value>cn/kinca/weboutlook/beans/ReceivedEmail.hbm.xml</value>
				<value>cn/kinca/weboutlook/beans/SentEmail.hbm.xml</value>
		    </list>
		</property>
		<property name="hibernateProperties">
			<value>
		        hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
		        hibernate.hbm2ddl.auto=update
		        hibernate.show_sql=true
		        hibernate.format_sql=false
		        hibernate.cache.use_second_level_cache=true
       	        hibernate.cache.use_query_cache=false
        	    hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
			</value>
		</property>
	</bean>
	<!-- 配置事务管理 操作数据库时要不全成功要不全失败-->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<!-- 配置事务传播特性,这里使用注解方式 -->
	<tx:annotation-driven transaction-manager="txManager"/>
	
	<!-- 交由Spring管理的Action类 -->
	<bean id="userService" class="cn.kinca.weboutlook.serviceimpl.UserServiceImpl"/>
	<bean id="emailService" class="cn.kinca.weboutlook.serviceimpl.EmailServiceImpl"/>
	<!-- cn.itcast.web.PersonAction类中的personService由spring通过注解注入上面personService的值,如果不通过注解需要加properties -->
	<bean id="userAction" class="cn.kinca.weboutlook.web.UserAction"/>
	<bean id="emailAction" class="cn.kinca.weboutlook.web.EmailAction"/>
</beans>

ServerImpl.java

@Transactional
public class EmailServiceImpl implements EmailService {
	@Resource private SessionFactory sessionFactory;
	public void emailadd(Email email) {
		sessionFactory.getCurrentSession().persist(email);
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Set<Email> emailload() {
		User user = (User) sessionFactory.getCurrentSession().get(User.class, (Integer)ActionContext.getContext().getSession().get("userid"));
		//这里有个懒加载的问题。使用openSessionInView好像不起作用,不的什么原因
		System.out.println(user.getEmails());
		return user.getEmails();
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public boolean checkUId(List<String> uIds,String uId){
		//遍历list内容,与uid比较
		System.out.println("-------------");
        for(String cUId:uIds){
        	System.out.println(cUId);
        	if(cUId.equals(uId))return false;
        }
		return true;
	}
	//从邮件服务器读取邮件并保存到系统数据库,并读取总的邮件条数
	public int loadReceivedEmail(int emailid) throws Exception {
		/**
		 * 注意UID与MessageID并非一个东西,
		 * UID是邮箱用来标识你这个账户的每一封邮件的东西,
		 * 而MessageID是发送邮件的时候生成的唯一ID,
		 * 也有可能发送没有你的接收邮箱自己生成,或者是javamail生成的,
		 * 总是取messageid需要下载邮件的头,这样有联网操作会很慢的,所以我们只需要存储下来uid就好了,
		 * 记得保存的时候按照邮箱存储,因为不同的邮箱uid会重复的,
		 * 至于规律最好别去参考有增的就有减的,所以还是安心的遍历吧,反正很快
		 */
		//Set<ReceivedEmail> receivedEmails=new HashSet();
		List<String> uIds=new ArrayList();
		List<ReceivedEmail> receivedEmails=new ArrayList();
		//配置邮件服务器连接信息
		Email email=(Email)sessionFactory.getCurrentSession().get(Email.class, emailid);
		Properties props = System.getProperties();   
        props.put("mail.smtp.host", email.getSmtp());   
        props.put("mail.smtp.auth", "true");   
        Session session = Session.getDefaultInstance(props, null);   
        URLName urln = new URLName("pop3", email.getPop3(), 110, null,   
                email.getEmail(), email.getPassword());   
        Store store = session.getStore(urln);   
        store.connect();   
        Folder folder = store.getFolder("INBOX");   
        folder.open(Folder.READ_ONLY);   
        Message message[] = folder.getMessages();   
        POP3Folder inbox = (POP3Folder) folder;
       // System.out.println("Messages's length: " + message.length);   
        EmailReceive pmm = null;   
        
        //从数据库中读取该邮箱对应的所有邮件的uid放入list集合中
        Criteria cr=sessionFactory.getCurrentSession().createCriteria(ReceivedEmail.class);
        cr.add(Restrictions.eq("belongemail.id", emailid));
        receivedEmails=cr.list();
        for(ReceivedEmail re:receivedEmails){
        	uIds.add(re.getUid());
        }
        //首先判断该邮件uid是否存在,如不存在则下载该邮件,否则不处理
        for (int i = 0; i < message.length; i++) {  
	        if(checkUId(uIds,inbox.getUID(message[i]))){
	        	try { 
	        		//下载邮件并放入/mail/用户名/receivedemails文件下
	        		String userPath=(String) ActionContext.getContext().getSession().get("username");
	        		String realpath=ServletActionContext.getServletContext().getRealPath("/mail/"+userPath+"/receivedemails");
	        		File emailFilePath=new File(new File(realpath),new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+".eml");
	        		if(!emailFilePath.getParentFile().exists())emailFilePath.getParentFile().mkdirs();
	        		OutputStream ips = new FileOutputStream(emailFilePath.getPath());
	        		message[i].writeTo(ips);
	        		ips.close();
		            pmm = new EmailReceive((MimeMessage) message[i]);  
		            ReceivedEmail receivedEmail=new ReceivedEmail();
		            receivedEmail.setUid(inbox.getUID(message[i]));
		            receivedEmail.setSender(pmm.getFrom());
		            receivedEmail.setToAddress(pmm.getMailAddress("to"));
		            receivedEmail.setCcAddress(pmm.getMailAddress("cc"));
		            receivedEmail.setBccAddress(pmm.getMailAddress("bcc"));
		            receivedEmail.setSubject(pmm.getSubject());
		            receivedEmail.setSendtime(pmm.getSentDate());
		            pmm.getMailContent((Part) message[i]);
		            receivedEmail.setContent(pmm.getBodyText());
		            
		            receivedEmail.setBelongemail(email);
	    
		            sessionFactory.getCurrentSession().persist(receivedEmail);
		            
		            //receivedEmails.add(receivedEmail);
		            /*String rmsg=null;
		            System.out.println("Message " + i + " subject: " + pmm.getSubject());   --
		            System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());   --
		            System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());   
		            System.out.println("Message " + i + " hasRead: " + pmm.isNew());   
		            System.out.println("Message " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i]));   
		            System.out.println("Message " + i + " form: " + pmm.getFrom());   --
		            System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));  -- 
		            System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));   --
		            System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));   --
		            pmm.setDateFormat("yy年MM月dd日 HH:mm");   
		            System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());   
		            System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());   
		            // 获得邮件内容===============   
		            pmm.getMailContent((Part) message[i]);   
		            System.out.println("Message " + i + " bodycontent: \r\n"   
		                    + pmm.getBodyText());   
		            pmm.setAttachPath("c:\\aaaa\\");    
		            pmm.saveAttachMent((Part) message[i]);  
		             
		            rmsg="Message " + i + " subject: " + pmm.getSubject()
		            	+"\r\nMessage " + i + " sentdate: "+ pmm.getSentDate()
		            	+"\r\nMessage " + i + " replysign: "+ pmm.getReplySign()
		            	+"\r\nMessage " + i + " hasRead: " + pmm.isNew()
		            	+"\r\nMessage " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i])
		            	+"\r\nMessage " + i + " form: " + pmm.getFrom()
		            	+"\r\nMessage " + i + " to: "+ pmm.getMailAddress("to")
		            	+"\r\nMessage " + i + " cc: "+ pmm.getMailAddress("cc")
		            	+"\r\nMessage " + i + " bcc: "+ pmm.getMailAddress("bcc");
		            pmm.setDateFormat("yy年MM月dd日 HH:mm");
		            rmsg = rmsg + "\r\nMessage " + i + " sentdate: "+ pmm.getSentDate()
		            	+"\r\nMessage " + i + " Message-ID: "+ pmm.getMessageId();
		            // 获得邮件内容===============   
		            pmm.getMailContent((Part) message[i]);   
		            rmsg = rmsg +"\r\nMessage " + i + " bodycontent: \r\n"   
		                    + pmm.getBodyText();   
		            pmm.setAttachPath("c:\\aaaa\\");    
		            pmm.saveAttachMent((Part) message[i]); 
		            OutputStream rms = new FileOutputStream("resource\\demo3.log",true);
		            rms.write(rmsg.getBytes());
		    		rms.close();
		    		*/
	        	} catch (Exception ex) {
	    			ex.printStackTrace();
	    		}
	        }
        }
        return ((Long)sessionFactory.getCurrentSession().createQuery("select count(*) from ReceivedEmail where belongemail.id=:emailid").setInteger("emailid", emailid).iterate().next()).intValue();  
       //System.out.println("receivedEmails.size()"+receivedEmails.size());
       //return receivedEmails;
	}

	//从数据库把邮件导入到set集合中并且在center页面显示,由于有分页,所以不考虑在loadReceivedEmail()方法中吧邮件放入set集合
	/* (non-Javadoc)
	 * @see cn.kinca.weboutlook.service.EmailService#showReceivedEmail(int, int)
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<ReceivedEmail> showReceivedEmail(int emailid,int page){
		List<ReceivedEmail> receivedEmails=new ArrayList();
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(ReceivedEmail.class);
		cr.add(Restrictions.eq("belongemail.id", emailid));
		cr.setFirstResult((page-1)*20);
		cr.setMaxResults(20);
		receivedEmails= cr.list();
		return receivedEmails;
	}
	
	//从email表读取发信email的pop3,smtp等信息
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Email loadEmailData(int emailid){
		return (Email) sessionFactory.getCurrentSession().get(Email.class, emailid);	
	}

	//保存发送的邮件到数据库
	public void saveSentEmail(SentEmail sentEmail) {
		sessionFactory.getCurrentSession().persist(sentEmail);	
	}
}