一、导入依赖
<!-- Spring上下文容器 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--Spring整合MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-typehandlers-jsr310</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- 事务管理依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- 连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<!-- junit 测试框架-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring测试框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.7.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
</dependency>
<!-- MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--tomcat-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.36</version>
</dependency>
二、搭建Spring 整合MyBatis环境
2.1、MyBatis配置类
@Configuration
@ComponentScan(basePackages = "com.project")
@EnableTransactionManagement
@MapperScan("com.project.dao")
public class MyBatisConfig {
// 数据源
@Bean
public DataSource getDataSource(){
DruidDataSource dataSource = new DruidDataSource();
// 完成数据源设置和连接池设置
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
// 如果url是来自xml配置文件,此时 要把-->&换成 -->&
dataSource.setUrl("jdbc:mysql://localhost:3306/ssmdemo?characterEncoding=utf-8&allowMultiQueries=true");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setMaxActive(50);
dataSource.setMinIdle(20);
dataSource.setMaxWait(1000);
return dataSource;
}
// SqlSessionFactory工厂配置
@Bean
public FactoryBean getFactory(){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(this.getDataSource());
factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
return factoryBean;
}
// 事务管理器
@Bean
public TransactionManager getTransactionManager(){
DataSourceTransactionManager trans =
new DataSourceTransactionManager();
trans.setDataSource(this.getDataSource());
return trans;
}
}
2.2、根据业务测试环境的搭建
2.2.1、业务接口
void addStu(StudentBean stu);
2.2.2、根据业务方法抽取出数据库操作,给出持久层方法,同时在资源目录下提供同包的映射文件
void addStu(StudentBean stu);
2.2.3、根据业务接口给出实现类
@Service
@Transactional
public class StudentServiceImpl implements IStudentService {
@Resource
private IStudentDao studentDao;
@Override
public void addStu(StudentBean studentBean) {
studentDao.addStu(studentBean);
}
}
2.2.4、在test包中利用测试框架完成测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyBatisConfig.class)
public class TestStuService {
@Resource
private IStudentService service;
@Test
public void testAll(){
service.addStu(new StudentBean("刘备",
LocalDate.parse("1000-01-01"),
"17294724564","男"));
}
}
三、加入SpringMVC配置类
@Configuration
@EnableWebMvc // 开启类型的自动转换
@Import(MyBatisConfig.class)
public class WebApplicationConfig implements WebMvcConfigurer {
// 请求映射处理适配器
@Autowired
private RequestMappingHandlerAdapter adapter;
// 设置响应信息的编码集
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringHttpMessageConverter
= (StringHttpMessageConverter)converters.get(1);
stringHttpMessageConverter.setDefaultCharset(Charset.forName("utf-8"));
}
// 提供静态资源的支持 请求的url以/html/开头,表示找类路径的/static/html/下的文件
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/html/**")
.addResourceLocations("classpath:/static/html/");
}
// 注册类型转换器
@PostConstruct
public void addConversionConfig() {
ConfigurableWebBindingInitializer initializer =
(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService converService = (GenericConversionService) initializer.getConversionService();
// 添加自定义转换器
converService.addConverter(new LocalDateTypeChange());
}
}
}
四、书写服务器和应用控制器测试SpringMVC的环境
4.1、Tomcat服务器
public class MainServer {
public MainServer(){
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
tomcat.getConnector();
Context context = tomcat.addContext("",null);
DispatcherServlet dispatcherServlet = new DispatcherServlet(
this.createApplicationContext(context.getServletContext())
);
Wrapper servlet = Tomcat.addServlet(context,
"dispatcherServlet",
dispatcherServlet);
servlet.setLoadOnStartup(1);
servlet.addMapping("/*");
try {
tomcat.start();
} catch (LifecycleException e) {
e.printStackTrace();
}
}
/**
* 创建SpringMVC的应用上下文对象
* @param servletContext servlet 上下文对象
* @return SpringMVC的应用上下文对象
*/
public WebApplicationContext createApplicationContext(ServletContext servletContext){
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
// 注入配置类
ctx.register(WebApplicationConfig.class);
ctx.setServletContext(servletContext);
ctx.refresh();
// 用于在非web应用中关闭IoC容器
ctx.registerShutdownHook();
return ctx;
}
public static void main(String[] args) {
new MainServer();
}
}
4.2提供应用控制器Controller
@Controller // 表示该类为应用控制器 且为SpringBean组件
public class TestController {
@Resource
private IStudentService service;
// 书写该方法的请求路径
@RequestMapping("test")
// 把数据写入HttpOutputStream中---既是把数据原样展示
@ResponseBody
public String test() {
return "hello world";
}
}
总结:SSM配置较SpringBoot配置较为麻烦。需要写很多配置,且需自己提供Tomcat启动器。所以后续写java项目时,建议使用SpringBoot!