SSM整合的配置

SSM整合

整合概述

Spring4.3.4+SpringMVC+Mybatis3.5.2整合

整合流程:

  1. 创建maven-webapp项目
  2. 导入相关依赖
  3. 添加配置文件(xml,注解)
  4. 编写java代码(entity,dao,service,dto,controller)

###数据库表

  • department
  • student

SSM整合依赖

<!--springframework JDBC与事务的相关依赖 (spring-jdbc,spring-tx)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.4.RELEASE</version>
</dependency>
<!--    spring内部日志实现 logback (logbak-classic、logback-core、slf4j-api)-->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

<!--spring-webmvc (spring-core、spring-context、spring-aop、spring-expression、spring-web、spring-webmvc)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.4.RELEASE</version>
</dependency>
<!--    aspectj支持库 (spring-aspects、aspectjweaver)-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.3.4.RELEASE</version>
</dependency>


<!--jackson spring支持json插件 (jackson-databind、jackson-annotations、jackson-core)-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
</dependency>
<!--myabtis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>
<!-- mybatis-spring  mybatis整合spring的插件-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.0</version>
</dependency>
<!-- log4j日志 mybatis使用的日志实现-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

<!--servlet相关依赖-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- junit4 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>

jdbc属性文件

# jdbc config
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=123456

#pool config
jdbc.maxActive=10
jdbc.maxWait=10000

基于XML的SSM整合

有关基于XML整合所需的配置文件:

  1. web.xml web项目核心启动配置
  2. applicationContext.xml spring容器核心配置
    1. jdbc.properties 数据库连接相关的配置
    2. mapper.xml dao中mapper接口的映射文件
  3. springMVC-servlet.xml springMVC核心配置
  4. 日志配置
    1. log4j.properties(mybatis使用的日志实现)
    2. logback.properties(springMVC使用的日志实现)
web.xml配置
  1. 上下文监听(监听spring核心配置的创建)
  2. springMVC核心控制器的servlet
  3. 过滤器配置

具体如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--    web context监听器,监听spring核心配置-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--    springmvc 中央控制器-->
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
applicationContext.xml配置
  1. 读取属性文件(加载jdbc相关的属性)
  2. 扫描bean组件
  3. 配置数据源Bean
  4. 配置SqlSessionFactoryBean
  5. 扫描Mybatis的Mapper
  6. 事务管理器

具体如下:

<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <!--    1.自动扫描bean组件 -->
    <context:component-scan base-package="com.softeem.ssm1"/>
    <!--    2.属性文件读取解析器-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--    3.数据源配置 druid dbcp c3p0 proxool h2-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
    </bean>
    <!--    4.SqlSessionFactoryBean配置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.softeem.ssm1.entity"/>
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
    </bean>
    <!--    5.Mapper接口扫描器-->
    <mybatis:scan base-package="com.softeem.ssm1.dao"/>
    <!--    6.事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

####SpringMVC-servlet.xml配置

  1. 驱动MVC的配置
  2. 扫描Controller组件
  3. 静态资源放行配置
  4. 视图解析器
<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--    1.驱动mvc注解(controller)配置-->
    <mvc:annotation-driven/>
    <!--    2.扫描controller组件-->
    <context:component-scan base-package="com.softeem.ssm1.controller"/>
    <!--    3.静态资源默认放行配置-->
    <mvc:default-servlet-handler/>

    <!--    <mvc:resources mapping="/static/**" location="/static/"/>-->

    <!--    4.视图解析器配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

零配置整合SSM

​ 思路与使用配置文件配置几乎一致,只不过将原本使用xml进行配置的信息使用纯java代码方式实现,零配置最终目的就是消除一切xml配置文件。

零配置的实现过程:

1. 创建web容器的启动器(等同于web.xml)
/**
 * webapp核心启动类,等同于web.xml
 * @Author mrchai
 * @Date 2019/10/12 16:39
 */
public class WepAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * 获取applicationContext核心配置(spring核心配置)
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{AppContextConfig.class};
    }

    /**
     * 获取springmvc核心配置
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebMvcConfig.class};
    }

    /**
     * 配置核心控制器DispatcherServlet 拦截规则(url-pattern)
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 配置过滤器
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        //创建编码过滤器
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("utf-8");
        encodingFilter.setForceResponseEncoding(true);
        return new Filter[]{encodingFilter};
    }
}

2. 创建Spring核心配置类(等同于applicationContext.xml)
@EnableAspectJAutoProxy
@ComponentScan("com.softeem.ssm2")
@MapperScan("com.softeem.ssm2.dao")
@EnableTransactionManagement
@PropertySource("classpath:jdbc.properties")
@Configuration
public class AppContextConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.maxActive}")
    private int maxActive;

    @Value("${jdbc.maxWait}")
    private long maxWait;

    /**
     * 数据源配置
     * @return
     */
    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxWait(maxWait);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setTypeAliasesPackage("com.softeem.ssm2.entity");

        //获取路径匹配解析器(读取映射文件)
        PathMatchingResourcePatternResolver pm = new PathMatchingResourcePatternResolver();
        //将映射文件读取为Resource数组
        Resource[] resources = pm.getResources("classpath:mappers/*.xml");
        bean.setMapperLocations(resources);

        //创建配置并设置
        org.apache.ibatis.session.Configuration cfg = new org.apache.ibatis.session.Configuration();
        cfg.setCacheEnabled(true);
        cfg.setLazyLoadingEnabled(false);
        cfg.setUseGeneratedKeys(true);
        bean.setConfiguration(cfg);

        return bean.getObject();
    }

    /**
     * 事务管理器
     * @return
     */
    @Bean
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }

}

3. 创建SpringMVC的核心配置类(等同于springmvc-servlet.xml)
@EnableWebMvc  //<mvc:annotation-driver>
@ComponentScan("com.softeem.ssm2.controller")
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    /**
     * 设置静态资源放行
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SSM整合配置文件的方式一般有两种:基于XML的配置和基于注解的配置。 1. 基于XML的配置 (1)在Spring配置文件中配置MyBatis和Spring的整合: ``` <!--配置MyBatis的SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean> <!--配置MyBatis的扫描器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xxx.mapper"/> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> ``` (2)在MyBatis的配置文件中配置数据源: ``` <dataSource type="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> ``` (3)在Spring配置文件中配置数据源的属性: ``` <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <util:properties id="jdbc" location="classpath:jdbc.properties"/> ``` 2. 基于注解的配置 (1)在Spring配置文件中配置MyBatis和Spring的整合: ``` <!--配置MyBatis的SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean> <!--配置MyBatis的扫描器--> <mybatis:scan base-package="com.xxx.dao"/> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> ``` (2)在Java类中使用注解配置数据源: ``` @Configuration @PropertySource("classpath:jdbc.properties") public class DataSourceConfig { @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } } ``` 注:以上代码中的数据源使用的是阿里巴巴的Druid连接池。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值