黑马程序员技术交流社区

标题: 【广州校区】+【原创】+ 免XML的SpringMVC配置之二——SSM整合 [打印本页]

作者: leeao    时间: 2018-1-25 10:52
标题: 【广州校区】+【原创】+ 免XML的SpringMVC配置之二——SSM整合
    之前写过一篇简单的免XML的SpringMVC配置,今天补充完整,写一个简单的免XML配置的SSM整合    首先还是写一个基本的javaConfig类
[Java] 纯文本查看 复制代码
@Configuration
@EnableWebMvc  //启动Spring MVC相关配置,相当于继承了WebMvcConfigurationSupport
@ComponentScan(basePackages = { "www.leeao"})  //配置包扫描
@Import(MyServiceConfig.class)  //导入其他配置类
@MapperScan("www.leeao.mapper") //mybatis包扫描
public class MyMvcConfig{

}


   这里引入了另一个配置类MyServiceConfig,这个配置类配置了数据源和mybatis相关配置
[Java] 纯文本查看 复制代码
@Configuration
@PropertySource("classpath:db.properties")
public class MyServiceConfig {
  @Autowired
  private Environment env;

  /**
   * 数据源
   * @return
   */
  @Bean(name = "dataSource", initMethod = "init" , destroyMethod = "close")
  public DataSource getDateSource(){
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(env.getProperty("jdbc_url"));
    druidDataSource.setUsername(env.getProperty("jdbc_user"));
    druidDataSource.setPassword(env.getProperty("jdbc_password"));
    druidDataSource.setInitialSize(env.getProperty("initialSize", Integer.class));
    druidDataSource.setMinIdle(env.getProperty("minIdle", Integer.class));
    druidDataSource.setMaxActive(env.getProperty("maxActive", Integer.class));
    druidDataSource.setMaxWait(env.getProperty("maxWait", Long.class));
    return druidDataSource;
  }

  /**
   *sqlSessionFactory
   * @return
   * @throws Exception
   */
  @Bean(name = "sqlSessionFactory")
  public SqlSessionFactory getSqlSessionFactory() throws Exception {
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(getDateSource());
    factoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:mybatis/mapper/*.xml"));
    factoryBean.setTypeAliasesPackage("www.leeao.domain");
    return factoryBean.getObject();
  }

  /**
   * 配置mapper接口的扫描
   * @return
   */
  @Bean
  public static MapperScannerConfigurer setMapperScannerConfigurer(){
    MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
    scannerConfigurer.setBasePackage("www.leeao.mapper");
    scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    return scannerConfigurer;
  }


    其他的action、entity、dao这里就不赘述了,这样,一个简单的免XML的SSM整合就完成啦

作者: Yin灬Yan    时间: 2018-1-25 13:29
我来占层楼啊




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2