该篇文章是上两篇maven入门博文的续集,读者可以选择先阅读前面的两篇再进行该篇的学习。本文主要讲述的是maven项目为什么要拆分和聚合工程(模块),以及如何拆分工程(模块)和聚合工程(模块)。
这里先简单给大家讲一下为什么有拆分和聚合。我们之前学了框架之后把ssm框架整合在一个工程或模块中,那在下次如果有项目用到相同的代码时,我们又得重新复制粘贴出来,这样即浪费内存又降低了开发的效率。maven工具已经给我们提供了一个解决方案,就是将每个层分开做成模块,然后再将每个层打包放到私服上,这也就是所说的拆分。拆分的好处是,每个层的编写可以分给专门的团队,然后其他层的团队可以直接引用私服中的包,总结起来就是分工明确,方便维护,提高效率,降低内存空间。我们做项目时候再引用这些包的过程叫聚合,聚合之后就形成了一个完整项目。
下面将演示如何用拆分和聚合思想搭建一个项目。
打开idea之后和之前创建maven项目一样,但是不同的是,这次可以选择site骨架来创建父工程
创建父工程之后,我们接着添加对应的三层模块。
父工程中要锁定各个依赖的版本,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.0modelVersion>
<groupId>com.stevensamgroupId>
<artifactId>maven_parentartifactId>
<version>1.0-SNAPSHOTversion>
<modules>
<module>maven_daomodule>
<module>maven_servicemodule>
<module>maven_webmodule>
modules>
<packaging>pompackaging>
<properties>
<spring.version>5.0.2.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<shiro.version>1.2.3shiro.version>
<mysql.version>5.1.6mysql.version>
<mybatis.version>3.4.5mybatis.version>
<spring.security.version>5.0.1.RELEASEspring.security.version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
dependencies>
dependencyManagement>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.8version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
<type>jartype>
<scope>compilescope>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.2version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-webartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-configartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-coreartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-taglibsartifactId>
<version>${spring.security.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.9version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
plugin>
plugins>
build>
project>
1.右键点击父工程,选择Module,不用骨架创建,输入模块名maven_dao,然后点下一步,完成即可。
2.创建dao模块之后,在main-java文件中创建该有的包,添加依赖
dao层中的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">
<parent>
<artifactId>maven_parentartifactId>
<groupId>com.stevensamgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>maven_daoartifactId>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.32version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.9version>
dependency>
dependencies>
project>
2.1.dao包和pojo包
dao层中的接口IStudentDao:
@Repository
public interface IStudentDao {
/**
* 查询所有的学生
* @return
*/
@Select("select * from student")
List<Student> findAll() throws Exception;
/**
* 保存一个学生
* @param student
*/
@Insert("insert into student(sname,sex,birthday,cno) values(#{sname},#{sex},#{birthday},#{cno})")
@Options(useGeneratedKeys = true,keyColumn = "sid",keyProperty = "sid")
void saveStudent(Student student);
2.2.在resources中将log4j.properties复制粘贴过来,创建jbdcConfig.properties和applicationContext-dao.xml
jbdcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web_test2
jdbc.username=root
jdbc.password=123
applicationContext-dao.xml:
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.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">
<context:property-placeholder location="classpath:jdbcConfig.properties" />
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="dataSource" ref="dataSource">property>
<property name="typeAliasesPackage" value="com.stevensam.pojo">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="configurer">
<property name="basePackage" value="com.stevensam.dao">property>
bean>
beans>
log4j.properties,值得注意的是,log4j.appender.LOGFILE.File表示日志的存放位置,可根据实际情况修改路径和文件名称。
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, 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=f:/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
3.DaoTest测试类:
package com.stevensam.test;
import com.stevensam.dao.IStudentDao;
import com.stevensam.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.InputStream;
import java.util.List;
/**
* author:seven lin
* date:2018/9/921:21
* description:dao测试类
**/
public class DaoTest {
private IStudentDao iStudentDao;
@Test
public void test() throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext-dao.xml");
iStudentDao = applicationContext.getBean(IStudentDao.class);
List<Student> studentList = iStudentDao.findAll();
for (Student stu:studentList) {
System.out.println(stu);
}
}
}
4.测试结果:
service层目录:
service层的pom文件:
<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">
<parent>
<artifactId>maven_parentartifactId>
<groupId>com.stevensamgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>maven_serviceartifactId>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>com.stevensamgroupId>
<artifactId>maven_daoartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
dependencies>
project>
applicationContext-service文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="applicationContext-dao.xml">import>
<context:component-scan base-package="com.stevensam.service.impl">context:component-scan>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice transaction-manager="transactionManager" id="interceptor">
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED">tx:method>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="tx" expression="execution(* com.stevensam.service.impl.*.*(..))">aop:pointcut>
<aop:advisor advice-ref="interceptor" pointcut-ref="tx">aop:advisor>
aop:config>
beans>
接口类和实现类:
IStudentService:
package com.stevensam.service;
import com.stevensam.pojo.Student;
import java.util.List;
/**
* author:seven lin
* date:2018/9/1010:02
* description:
**/
public interface IStudentService {
/**
* 查询所有的学生
* @return
*/
List<Student> findAll() throws Exception;
/**
* 保存一个学生
* @param student
*/
void saveStudent(Student student) throws Exception;
/**
* 更新学生信息
* @param student
*/
void updateStudent(Student student) throws Exception;
/**
* 根据学生的id删除学生信息
* @param sid
*/
void deleteById(Integer sid) throws Exception;
}
实现类StudentService:
package com.stevensam.service.impl;
import com.stevensam.dao.IStudentDao;
import com.stevensam.pojo.Student;
import com.stevensam.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* author:seven lin
* date:2018/9/1010:09
* description:
**/
@Service
public class StudentService implements IStudentService {
@Autowired
private IStudentDao iStudentDao;
public List<Student> findAll() throws Exception {
return iStudentDao.findAll();
}
public void saveStudent(Student student) throws Exception {
iStudentDao.saveStudent(student);
int a=1/0;//测试事务
iStudentDao.saveStudent(student);
}
public void updateStudent(Student student) throws Exception {
}
public void deleteById(Integer sid) throws Exception {
}
}
测试类:
import com.stevensam.pojo.Student;
import com.stevensam.service.IStudentService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* author:seven lin
* date:2018/9/1010:11
* description:service层测试类
**/
public class TestService {
private IStudentService iStudentService;
@Test
public void test() throws Exception {
ApplicationContext ac =new ClassPathXmlApplicationContext("classpath:applicationContext-service.xml");
iStudentService = ac.getBean(IStudentService.class);
List<Student> studentList = iStudentService.findAll();
for(Student stu:studentList){
System.out.println(stu);
}
}
}
测试结果:
控制层目录:
pom.xml引进service层的依赖:(注意打包方式要设置为war方式,其他两层设置为jar方式)
<dependencies>
<dependency>
<groupId>com.stevensamgroupId>
<artifactId>maven_serviceartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
dependencies>
StudentController控制类:
package com.stevensam.controller;
import com.stevensam.pojo.Student;
import com.stevensam.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
/**
* author:seven lin
* date:2018/9/1010:55
* description:
**/
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService iStudentService;
@RequestMapping("/findAll")
public ModelAndView findAll() throws Exception {
List<Student> studentList = iStudentService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("studentlist",studentList);
mv.setViewName("list");
return mv;
}
@RequestMapping("/saveStudent")
public String saveStudent(Student student) throws Exception {
iStudentService.saveStudent(student);
return "redirect:/student/findAll";
}
}
在web.xml中配置前端控制器和中文乱码过滤器,静态资源过滤等:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:sprignmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext-service.xmlparam-value>
context-param>
<error-page>
<error-code>404error-code>
<location>/WEB-INF/pages/404.jsplocation>
error-page>
web-app>
编写index.jsp:
<%--
Created by IntelliJ IDEA.
User: soso
Date: 2018/9/10
Time: 15:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
主页
查询所有学生
这里注意的是生日的格式为date,在前端传到后端的格式统统都为string,所以我们还需要配置一个自定义的类型转换器,StringtoDateConverter用于将字符串转换成日期格式,否则会出错。
package com.stevensam.utils;
import com.sun.tools.javac.util.StringUtils;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* author:seven lin
* date:2018/9/1014:46
* description:
**/
public class StringtoDateConverter implements Converter<String,Date> {
@Override
public Date convert(String s) {
//判断字符串是否符合规范
if(s != null && !"".equals(s)){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = dateFormat.parse(s);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}else
throw new RuntimeException();
return null;
}
}
为了提高用户的体验,如果出现了异常,我们将之前的异常都交由异常处理器处理,然后再转换到异常的页面error.jsp,当然内容很简单。
先写一个自定义的异常类集成的是Exception,MyException:
package com.stevensam.exception;
/**
* author:seven lin
* date:2018/9/1011:16
* description:
**/
public class MyException extends Exception {
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MyException(String message){
this.message = message;
}
}
再编写一个异常处理器类MyExceptionHandler:
package com.stevensam.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* author:seven lin
* date:2018/9/1011:18
* description:
**/
public class MyExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//先打印原异常信息在控制台上
e.printStackTrace();
//将该异常转换到一个异常界面上
MyException myException = null;
if(e instanceof MyException){
myException = (MyException) e;
}else{
myException = new MyException("未知错误,请联系管理员!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",myException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
根据以上的配置,最终编写控制层的配置文件sprignmvc.xml代码如下:
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.stevensam.controller">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/WEB-INF/pages/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:default-servlet-handler>mvc:default-servlet-handler>
<bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="service">
<property name="converters">
<set>
<bean class="com.stevensam.utils.StringtoDateConverter">bean>
set>
property>
bean>
<mvc:annotation-driven conversion-service="service">mvc:annotation-driven>
<bean class="com.stevensam.exception.MyExceptionHandler" id="exceptionHandler">bean>
beans>
运行项目有三种方式:第一种是直接用父工程中的tomcat7:run命令运行,第二种是用我们自带的tomcat去运行,还有一种是运行web层中的tomcat7:run命令。
在上面的运行方式中,如果直接运行web模块,那么会出现找不到依赖service的错误,这是因为在运行的时候控制层会去本地仓库找jar包,找不到就去私服里面找,再找不到再去中央仓库找,中央仓库自然不会收录我们项目的jar包,所以会报错。在此背景下,我们开发完一个模块之后,将jar包上传公司的私服上,以便其他同事使用,那么接下来就是讲解上传私服的步骤。
第一步: 需要在客户端即部署ssm_dao工程的电脑上配置 maven环境,并修改 settings.xml 文件,配置连接私服的用户和密码 。
此用户名和密码用于私服校验,因为私服需要知道上传的账号和密码是否和私服中的账号和密码一致。
<server>
<id>releasesid>
<username>adminusername>
<password>admin123password>
server>
<server>
<id>snapshotsid>
<username>adminusername>
<password>admin123password>
server>
第二步: 配置项目pom.xml
配置私服仓库的地址,本公司的自己的jar包会上传到私服的宿主仓库,根据工程的版本号决定上传到哪个宿主仓库,如果版本为release则上传到私服的release仓库,如果版本为snapshot则上传到私服的snapshot仓库
<distributionManagement>
<repository>
<id>releasesid>
<url>http://localhost:8081/nexus/content/repositories/releases/url>
repository>
<snapshotRepository>
<id>snapshotsid>
<url>http://localhost:8081/nexus/content/repositories/snapshots/url>
snapshotRepository>
distributionManagement>
注意:pom.xml这里 和 settings.xml 配置 对应!
第三步:测试
将项目dao和service工程打成jar包发布到私服:
1、首先启动nexus
2、对maven_dao执行deploy命令,结果如下所示。maven_service工程也是一样的操作。
注意事项:至于上传到私服的哪一个版本取决于项目中pom.xml中配置的版本,这里所有的版本都设定了1.0-SNAPSHOT,所以上传的是测试版本。
上传完成之后,这个时候实际上还不能真正的运行成功。我们在本地仓库中删掉上传的service的jar包之后,再运行web模块,会失败,提示找不到该依赖。因为我们还没有配置从私服上下载jar包。配置的步骤如下:
在客户端的setting.xml中配置私服的仓库,由于setting.xml中没有repositories的配置标签需要使用profile定义仓库。
<profile>
<id>devid>
<repositories>
<repository>
<id>nexusid>
<url>http://localhost:8081/nexus/content/groups/public/url>
<releases>
<enabled>trueenabled>
releases>
<snapshots>
<enabled>trueenabled>
snapshots>
repository>
repositories>
<pluginRepositories>
<pluginRepository>
<id>publicid>
<name>Public Repositoriesname>
<url>http://localhost:8081/nexus/content/groups/public/url>
pluginRepository>
pluginRepositories>
profile>
使用profile定义仓库需要激活才可生效:
<activeProfiles>
<activeProfile>devactiveProfile>
activeProfiles>
删除掉本地仓库service层,再运行web模块即可看到从私服中下载的信息。