02_Maven依赖管理

Maven工程的拆分与聚合(重点)

一个完整的早期开发好的crm项目,现在要使用maven工程对它进行拆分,这时候就可以将dao拆解出来形成表现独立的工程,同样service,action也都这样拆分


拆分与聚合

工程拆分之后,将来还要聚合(聚合就是将拆分的工程进一步组合在一起,又形成一个完整的项目)
为了达到聚合的目标,所以今天会引入
父工程(maven project)
子模块(maven module) dao ,service, web

开发步骤:

  1. 新建项目,和之前一样,在这里只标注不一样的地方,项目命名ssh_parent

    新建父项目

    父工程目录结构
    父工程目录结构

    从它的目录结构可以看出,父工程本身不写代码,它里面有一个pom.xml文件,这个文件可以将多个子模块中通用的jar所对应的坐标,集中在父工程中配置,将来的子模块就可以不需要在pom.xml中配置通用jar的坐标了

  2. 如何创建父工程的子模块


    新建Module

    Next

    Next
  3. 再次查看父工程的pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.huachao</groupId>
  <artifactId>ssh_parent</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <modules>
    <module>ssh_dao</module>
  </modules>
</project>
  1. 查看子模块的pom.xml,发现多了一个 parent结点
<parent>
    <groupId>com.huachao</groupId>
    <artifactId>ssh_parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>

并且内部所包含的结点,其实就是父工程的坐标
坐标=groupId+artifactId+version
组织名 项目名 版本

  1. 在父工程ssh_parentpom.xml中,添加struts2和hibernate的jar
    jar包

    查看依赖包
    查看依赖包

    发现在struts2hibernate中有javassist,存在包冲突的问题
    解决方案一:排除依赖
    解决包冲突问题,我们需要屏蔽掉strutrs中低版本的javassist
    步骤:
    javassist:3.11.0.GA上右键点击------>Exclude Maven Artifact
    屏蔽包冲突
Next

最后点击保存,会自动刷新

只剩下一个javassist包

查看pom.xml是怎么处理的
加了exclusions标签

xml屏蔽jar包的处理方式

解决方案二:依赖调节原则
maven自动按照下边的原则调解:

  1. 第一声明者优先原则
    在pom文件定义依赖,先声明的依赖为准。就是谁在前面声明,就依赖谁
  2. 路径近者优先原则
    例如:A依赖 spirng-beans-4.2.4,A依赖B,B依赖 spirng-beans-3.0.5,则spring-beans-4.2.4优先被依赖在A中,因为spring-beans-4.2.4相对spirng-beans-3.0.5被A依赖的路径最近。

解决冲突一般做法:

  • 排除依赖,使用exclusionsexclusion标签,图形化操作参考上面
<!-- 排除 spring-beans-->
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
        </exclusions>

  • 锁定版本
    面对众多的依赖,有一种方法不用考虑依赖路径、声明优化等因素可以采用直接锁定版本的方法确定依赖构件的版本,版本锁定后则不考虑依赖的声明顺序或依赖的路径,以锁定的版本的为准添加到工程中,此方法在企业开发中常用。
    如下的配置是锁定了spring-beans和spring-context的版本:
  <dependencyManagement>
    <dependencies>
        <!--这里锁定版本为4.2.4 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
    </dependencies>
  </dependencyManagement>

注意:在工程中锁定依赖的版本并不代表在工程中添加了依赖,如果工程需要添加锁定版本的依赖则需要单独添加<dependencies></dependencies>标签,如下:

<dependencies>
        <!--这里是添加依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
    </dependencies>

上边添加的依赖并没有指定版本,原因是已在<dependencyManagement>中锁定了版本,所以在<dependency>下不需要再指定版本。

一份已经调好的框架的jar包的pom.xml(项目中可以直接使用)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.huachao</groupId>
  <artifactId>ssh_parent</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <modules>
    <module>ssh_dao</module>
    <module>ssh_service</module>
    <module>ssh_web</module>
  </modules>
  <!-- 为了确定每个框架的版本号 -->

  <!-- 锁定版本 -->
      <properties>
        <!-- 定义版本常量 -->
        <spring.version>4.2.4.RELEASE</spring.version>
        <struts2.version>2.3.24</struts2.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <shiro.version>1.2.3</shiro.version>
        <cxf.version>3.0.1</cxf.version>
        <c3p0.version>0.9.1.2</c3p0.version> 
        <mysql.version>5.1.6</mysql.version>
    </properties>
    <!-- 锁定版本,struts2-2.3.24、spring4.2.4、hibernate5.0.7 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>${hibernate.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
                <version>${struts2.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-spring-plugin</artifactId>
                <version>${struts2.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>
  
  <dependencies>
    <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.37</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.1</version>
        </dependency>
        <!-- <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency> -->
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.1</version>
        </dependency>
    
        <!-- jstl -->
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        
        <!-- shiro -->
         <!-- apache shiro dependencies -->
         <!-- <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>${shiro.version}</version>
         </dependency> -->

      
       <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</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-web</artifactId>
          <version>${spring.version}</version>
        </dependency>

        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>${spring.version}</version>
        </dependency>
        
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>${spring.version}</version>
        </dependency>
        
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
        </dependency>
        
    
        
        <!-- struts2  begin -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>javassist</artifactId>
                    <groupId>javassist</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <!-- struts2  end -->
        
        <!-- hibernate begin -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <!-- hibernate end -->
        
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        
        <!-- <dependency> 
            <groupId>org.apache.cxf</groupId> 
            <artifactId>cxf-rt-frontend-jaxws</artifactId> 
            <version>${cxf.version}</version> 
        </dependency> 
        <dependency> 
            <groupId>org.apache.cxf</groupId> 
            <artifactId>cxf-rt-transports-http</artifactId> 
            <version>${cxf.version}</version> 
        </dependency> -->
        
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        
        <!-- Javamail -->
    <!--     <dependency>
          <groupId>javax.mail</groupId>
          <artifactId>mail</artifactId>
          <version>1.4.4</version>
        </dependency> -->
        
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    
        <dependency>
            <groupId>org.codehaus.xfire</groupId>
            <artifactId>xfire-core</artifactId>
            <version>1.2.6</version>
        </dependency> 
        
        <dependency>
           <groupId>dom4j</groupId>
           <artifactId>dom4j</artifactId>
           <version>1.6</version>
        </dependency>
    
        <!-- <dependency> 
            <groupId>org.apache.poi</groupId> 
            <artifactId>poi</artifactId> 
            <version>3.11</version> 
        </dependency>
        <dependency> 
            <groupId>org.apache.poi</groupId> 
            <artifactId>poi-ooxml</artifactId> 
            <version>3.11</version> 
        </dependency>
        <dependency> 
            <groupId>org.apache.poi</groupId> 
            <artifactId>poi-ooxml-schemas</artifactId> 
            <version>3.11</version> 
        </dependency> -->
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
       
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
       <!--  <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.4.0</version>
        </dependency> -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.6</version>
        </dependency>
  </dependencies>
  
   <build>
    <finalName>crmssh</finalName>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
  </build>
</project>

依赖关系

依赖具有传递性,但不是无限传递的,传递的规则如下:

传递依赖

解决方法:
如果在依赖传递过程中,导致jar包丢失,我们的做法很简单,就是再导入一次坐标

Maven整合SSH框架

父工程与Dao的Module整合

  • 新建Maven Project,名称为ssh_parent,打包类型选择pompom.xml使用上面已经调好的配置
  • 新建Maven Module,名称为ssh_dao项目,Parent Project选择ssh_parent,打包类型选择jar
  • 编写Customer的实例,已经对应的hibernate映射文件
package com.huachao.crm.domain;
import java.io.Serializable;
/**
 * po的规范  (Persistent Object 持久化对象)
 * 1.公有类
 * 2.私有属性
 * 3.公有的getter与setter
 * 4.不能使用final修饰
 * 5.提供默认无参构造
 * 6.如果是基本类型,就写它对应的包装类
 * 7.一般都要实现java.io.Serializable
 * @author Administrator
 */
public class Customer implements Serializable {
    private Long custId;
    private String custName;
    private Long custUserId;
    private Long custCreateId;
    private String custIndustry;
    private String custLevel;
    private String custLinkman;
    private String custPhone;
    private String custMobile;
    public Long getCustId() {
        return custId;
    }
    public void setCustId(Long custId) {
        this.custId = custId;
    }
    public String getCustName() {
        return custName;
    }
    public void setCustName(String custName) {
        this.custName = custName;
    }
    public Long getCustUserId() {
        return custUserId;
    }
    public void setCustUserId(Long custUserId) {
        this.custUserId = custUserId;
    }
    public Long getCustCreateId() {
        return custCreateId;
    }
    public void setCustCreateId(Long custCreateId) {
        this.custCreateId = custCreateId;
    }
    public String getCustIndustry() {
        return custIndustry;
    }
    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }
    public String getCustLevel() {
        return custLevel;
    }
    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }
    public String getCustLinkman() {
        return custLinkman;
    }
    public void setCustLinkman(String custLinkman) {
        this.custLinkman = custLinkman;
    }
    public String getCustPhone() {
        return custPhone;
    }
    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }
    public String getCustMobile() {
        return custMobile;
    }
    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }
}

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-3-7 15:22:16 by Hibernate Tools 4.3.1.Final -->
<hibernate-mapping>
    <class name="com.huachao.crm.domain.Customer" table="cst_customer" >
        <id name="custId" type="java.lang.Long">
            <column name="cust_id" />
            <!-- 6种生成策略  : identity,native,sequence,uuid,increment, assigned  -->
            <generator class="identity" />
        </id>
      
        <property name="custName" type="string">
            <column name="cust_name" length="32" not-null="true"></column>
        </property>
        <property name="custUserId" column="cust_user_id"></property>
        <property name="custCreateId" column="cust_create_id"></property>
        <property name="custIndustry" column="cust_industry"></property>
        <property name="custLevel" column="cust_level"></property>
 
        <property name="custLinkman" type="string">
            <column name="cust_linkman" length="64"></column>
        </property>
        <property name="custPhone" type="string">
            <column name="cust_phone" length="64"></column>
        </property>
        <property name="custMobile" type="string">
            <column name="cust_mobile" length="16"></column>
        </property>
       
    </class>
</hibernate-mapping>
  • CustomerDao接口和实现类
package com.huachao.crm.dao;
import java.util.List;
import com.huachao.crm.domain.Customer;

public interface CustomerDao {
    /**
     * 查询出Customer 表中的所有记录
     * @return
     */
    public List<Customer> findAll();
}
package com.huachao.crm.dao.imp;
import java.util.List;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.huachao.crm.dao.CustomerDao;
import com.huachao.crm.domain.Customer;

public class CustomerDaoImp extends HibernateDaoSupport implements CustomerDao{
    @Override
    public List<Customer> findAll() {
        return (List<Customer>) this.getHibernateTemplate().find("from Customer");
    }

}
  • hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>

        <property name="show_sql">true</property>
        <property name="format_sql">false</property>
        <property name="hbm2ddl.auto">update</property>
        <!-- 懒加载,配合web.xml中配置的 openSessionInViewFilter -->
        <property name="hibernate.enable_lazy_load_no_trans">true</property>
        <!--校验模式  JPA  java persistent api-->
        <property name="javax.persistence.validation.mode">none</property>
        
        <!--  加载映射文件-->
        <mapping resource="com/huachao/crm/domain/Customer.hbm.xml"></mapping>
    
    </session-factory>
    </hibernate-configuration>
  • log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
  • applicationContext-dao.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop    
    http://www.springframework.org/schema/aop/spring-aop.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- dataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/hibernate_day04?characterEncoding=utf8" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>
    
    <!-- SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>
    
    <bean id="customerDao" class="com.huachao.crm.dao.imp.CustomerDaoImp">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
</beans>
  • 测试方法
package cn.huachao.test;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.huachao.crm.dao.CustomerDao;
import com.huachao.crm.domain.Customer;

public class CustomerTest {
    @Test
    public void testFindAll(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext-dao.xml");
        CustomerDao customerDao = (CustomerDao) ac.getBean("customerDao");
        
        List<Customer> list = customerDao.findAll();
        System.out.println(list.size());
    }
}
  • 测试在testFindAll方法上右键----->Run As----->Junit Test

与Service的Module整合

  • 新建Maven Module,名称为ssh_service项目,Parent Project选择ssh_parent,打包类型选择jar

  • ssh_service需要使用ssh_dao中Customer的实例类和方法,需要导入ssh_dao的jar包
    ssh_servicepom.xml

    导入ssh_dao

  • CustomerService接口和实现类

package com.huachao.crm.service;
import java.util.List;
import com.huachao.crm.domain.Customer;

public interface CustomerService {
    /**
     * 查询所有客户列表
     * 
     * @return
     */
    public List<Customer> findAll();
}
package com.huachao.crm.service.impl;
import java.util.List;
import com.huachao.crm.dao.CustomerDao;
import com.huachao.crm.domain.Customer;
import com.huachao.crm.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {
    //注值
    private CustomerDao customerDao;
    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }
    public List<Customer> findAll() {
        return customerDao.findAll();
    }
}
  • applicationContext-service.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop    
    http://www.springframework.org/schema/aop/spring-aop.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--  事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- aop -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.huachao.crm.service.impl.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    <!-- service -->
    <bean id="customerService" class="com.huachao.crm.service.impl.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"/>
    </bean>
</beans>

与Web的Module整合

  • 新建Maven Module,名称为ssh_web项目,Parent Project选择ssh_parent,打包类型选择war
  • 新建完报错,在Deployed Resources/webapp下新建WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <!--spring配置文件的加载的监听 器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>

    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--2.懒加载 OpenSessionInviewFilter noSession or session is closed -->
    <filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>

        </init-param>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>

    </filter>
    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>

    </filter-mapping>
    <!--3.struts2核心控制器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  • ssh_web需要使用ssh_service中类和方法,需要导入ssh_service的jar包
    ssh_webpom.xml

    导入ssh_service

  • 编写CustomerAction

package com.huachao.crm.action;
import java.util.List;
import com.huachao.crm.domain.Customer;
import com.huachao.crm.service.CustomerService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport {
    private static final long serialVersionUID = -4325471976423944510L;
    private CustomerService customerService;
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
    @Override
    public String execute() throws Exception {
        List<Customer> list = customerService.findAll();
        System.out.println(list.size());
        
        ActionContext.getContext().put("list", list);
        return SUCCESS;
    }
}
  • applicationContext-web.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop    
    http://www.springframework.org/schema/aop/spring-aop.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="customerAction" class="com.huachao.crm.action.CustomerAction">
        <property name="customerService" ref="customerService"/>
    </bean>
</beans>
  • struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
        <action name="crm" class="customerAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
    
</struts>
  • spring配置文件整合,applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop    
    http://www.springframework.org/schema/aop/spring-aop.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">
    <import resource="classpath:applicationContext-web.xml"/>
    <!-- 有些时候,不加*号是找不到这个xml文件的 -->
    <import resource="classpath*:applicationContext-dao.xml"/>
    <import resource="classpath*:applicationContext-service.xml"/>
</beans>
  • Deployed Resources/webapp下新建success.jsp,查询成功跳转到该界面
    从域中取出数据,显示出来
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    ${list }
</body>
</html>

运行的第一种方式

  • 添加项目到Tomcat


    添加项目到Tomcat
  • 添加ssh_web项目

    添加`ssh_web`项目

  • Degbug 运行,或者Start运行


    运行
  • 访问路径
    http://localhost:8080/crmssh/crm

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容