手把手教自己使用Java形式配置SSM框架

本文详细介绍使用Java配置实现SSM框架的全过程,包括MyBatis配置、数据访问层、业务逻辑层及表示层的配置,同时提供Spring入口配置及web.xml替代方案,附带代码示例供读者直接应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说直接上代码,

不懂springIoC容器注入的阅读一下https://blog.youkuaiyun.com/Black1499/article/details/85272039;

有关xml方式配置ssm框架的可以看一下https://blog.youkuaiyun.com/Black1499/article/details/83961684,可以和下面的java配置的形式对比一下。

一、配置MyBatis

这里关于properties配置文件的读取,我采用了混合搭配的形式,就不再一个一个详细说明了。

  • 一种是注入Enviroment类,通过它的方法来读取对应的值

  • 一种是SpringEL表达式读取注入

      @Component
      @EnableTransactionManagement //该注解配置spring事务管理
      public class MybatisConfig {
      
          @Value("${jdbc.driver}")
          private String driver;
      
          @Autowired
          private Environment environment;
      
          @Bean("dataSource")
          public DataSource dataSourceConfig() throws PropertyVetoException {
              // 使用c3p0连接池
              ComboPooledDataSource source = new ComboPooledDataSource();
              source.setDriverClass(driver);
              source.setJdbcUrl("jdbc:mariadb://localhost:3306/testdb");
              source.setUser(environment.getProperty("jdbc.user"));
              source.setPassword("123456");
              return source;
          }
      
          @Bean("sqlSessionFactoryBean")
          public SqlSessionFactoryBean sqlSessionFactoryBeanConfig() throws PropertyVetoException, IOException {
              SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
              factoryBean.setDataSource(this.dataSourceConfig());
              factoryBean.setTypeAliasesPackage("com.lzx.entity");
              factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
              PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
              factoryBean.setMapperLocations(resolver.getResources("mappers/*.xml"));
              return factoryBean;
          }
      
          @Bean("transactionManager")
          public DataSourceTransactionManager dataSourceTransactionManagerConfig() throws PropertyVetoException {
              return new DataSourceTransactionManager(this.dataSourceConfig());
          }
      
      
          // JdbcTemplate
          @Bean
          public JdbcTemplate  jdbcTemplateConfig() throws PropertyVetoException {
              return new JdbcTemplate(dataSourceConfig());
          }
      }
    

二、配置数据访问层

@Configuration // 该注解表示这个类是一个配置类
@ComponentScan(basePackages = "com.lzx.dao") // 扫描数据访问层
@PropertySource("classpath:jdbc.properties") // 读取properties配置文件
@Import(MybatisConfig.class) // 导入MyBatis的配置
public class SpringDaoConfig  {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean("mapperScannerConfigurer")
    public MapperScannerConfigurer mapperScannerConfigurerConfig() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        configurer.setBasePackage("com.lzx.dao");
        return configurer;
    }
}

三、配置业务逻辑层

@ComponentScan(basePackages = "com.lzx.service") // 扫描业务逻辑层
@Configuration
public class SpringServiceConfig {
}

四、配置表示层

@ComponentScan(basePackages = "com.lzx.web")
@Configuration
@EnableWebMvc // 表明该类是配置controller的
public class SpringWebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/jsp/", ".jsp");
    }

//    @Bean
//    public InternalResourceViewResolver internalResourceViewResolverConfig() {
//        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
//        resolver.setViewClass(JstlView.class);
//        resolver.setPrefix("/WEB-INF/jsp/");
//        resolver.setSuffix(".jsp");
//        return resolver;
//    }

    @Bean
    public StandardServletMultipartResolver multipartResolverConfig() {
        return new StandardServletMultipartResolver();
    }
}

五、去除web.xml,采用java配置

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { SpringWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
		// 配置页面映射路径
        return new String[] { "/" };
    }

    @Override
    protected Filter[] getServletFilters() {
		// 配置机制编码防止乱码
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8");
        return new Filter[]{characterEncodingFilter};
    }
}

六、配置Spring入口

注意上面的所有配置文件建议大家放到一个包内。

@Configuration
@ComponentScan(basePackages = {"com.lzx.config"},
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)}
)
@EnableAspectJAutoProxy // 配置spring aop
public class RootConfig {
}

简单说明一下 @ComponentScan 注解的作用。由于我把所有的配置文件放到了一个名为config的包内,所以我们要统一扫描一下,但是要把Spring MVC给排除掉。因为spring为父容器,mvc是子容器。如果把mvc也注入到spring中,controller类会报错。二者是依赖管理,mvc里面的bean可以被spring使用,但是mvc不能使用spring里面的bean。所以要把mvc给排除掉。

代码分享

直接拿去使用,注意更改相关包的路径
https://github.com/Black1499/ssm_spring_study/tree/master/src/main/java/com/lzx/config

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值