当前位置:网站首页>完全注解的ssm框架搭建
完全注解的ssm框架搭建
2022-07-01 21:43:00 【_小许_】
使用配置文件有时比较麻烦,spring可以实现完全注解开发。
spring注解开发基础
使用配置文件启动IoC容器的对象是ClassPathXmlApplicationContext
而使用配置类启动IoC容器的对象是AnnotationConfigApplicationContext
。
配置类
import com.ssm.pojo.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringContextConfig {
@Bean
public Test test1(){
return new Test();
}
}
启动程序
import com.ssm.config.SpringContextConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.applet.AppletContext;
public class ConfigTest {
@Test
public void test1(){
ApplicationContext context=new AnnotationConfigApplicationContext(SpringContextConfig.class);
com.ssm.pojo.Test test = context.getBean(com.ssm.pojo.Test.class);
}
}
spring配置类
@Configuration配置类注解
@ComponentScan(“com.ssm.controller”) 组件扫描位置注解
@Configuration
@ComponentScans({
@ComponentScan("com.ssm.pojo"),@ComponentScan("com.ssm.dao"),@ComponentScan("com.ssm.service")}) //组件扫描位置,除控制器扫描所有类
public class SpringContextConfig{
@Bean
public Test test1(){
return new Test();
}
}
该类是根配置类相当于spring-context.xml
进行spring的相关配置,可以通过@Bean
注解将java对象注入到IoC容器中也可以使用@ComponentScans
配置扫描的位置,开启注解扫描。
spring mvc配置类
在spring中我们可以通过用java代码配置bean,而不使用xml (相当于applicationContext.xml),改成使用java代码来实现javabean的配置:
@Configuration //定义是spring的bean配置类
@ComponentScan("com.ex.test") //扫描包
@Import(other.class) //导入config
public class ApplicationContext{
@Bean
public User user(){
return new User();}
}
而WebMvcConfigurer
配置类其实是Spring内部的一种配置方式,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter等等的东西对springmvc框架进行配置。(相当于spring-mvc.xml),除了该类还有其他几个类具有同样的功能:
spring mvc的注解开发,自定义配置类的三种方式:(使用了前2种方式时,不读取application.yml的配置,需要重写某些方法来保证一些默认的配置)
- @EnableWebMvc+implements WebMvcConfigurer;不使用@EnableAutoConfiguration中的设置
- extends WebMvcConfigurationSupport;不使用@EnableAutoConfiguration中的设置
- implements WebMvcConfigurer;使用@EnableAutoConfiguration中的设置
进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan("com.ssm.controller")
@EnableWebMvc
public class SpringWebmvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/../.html").addResourceLocations("/");
registry.addResourceHandler("/../.js").addResourceLocations("/");
registry.addResourceHandler("/../.css").addResourceLocations("/");
registry.addResourceHandler("/../.png").addResourceLocations("/");
} //配置视图解析器,资源管理器,拦截器等
}
同样也要开启注解扫描,释放静态资源。
web容器、web容器的配置文件web.xml及web容器的配置类
web容器实际上就是servlet,依托于web服务器来运行,web.xml是web容器的配置文件,早web服务器启动时自动加载。在ssm框架中,不需要servlet,进而取代的是DispatcherServlet总web容器,用来处理所有请求。web.xml也是其配置文件。
spring mvc框架中自带DispatcherServlet,只需要在配置文件web.xml
中配置。在完全注解开发不需要在web.xml中配置任何东西。那么该如何配置DispatcherServlet呢?代替方案是web容器的初始化对象WebApplicationInitializer
是随web应用启动而加载的 (相当于web.xml)。AbstractAnnotationConfigDispatcherServletInitializer
是已配置了DispatcherServle继承自AbstractDispatcherServletInitializer
该类又集成WebApplicationInitializer(web.xml),于是通过继承后只需要进行属性的配置。
现在JavaConfig配置方式在逐步取代xml配置方式。而WebApplicationInitializer可以看做是Web.xml的替代,它是一个接口。通过实现WebApplicationInitializer,在其中可以添加servlet,listener等,在加载Web项目的时候会加载这个接口实现类,从而起到web.xml相同的作用。
AbstractDispatcherServletInitializer也能对DispacherServlet配置,但是AbstractAnnotationConfigDispatcherServletInitializer更简单。
import com.ssm.config.SpringContextConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/** * 该类相当于web.xml主要用来配置DispatcherServlet和加载spring相关的配置类 * 目的是在tomcat启动时加载IoC容器 */
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
//该类随tomcat的启动自动加载
@Override
protected Class<?>[] getRootConfigClasses() {
// 根容器配置类
return new Class[]{
SpringContextConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// web-mvc容器配置类
return new Class[]{
SpringWebmvcConfig.class};
}
@Override
protected String[] getServletMappings() {
// 设置拦截的路径
return new String[]{
"/","*.action"};
}
}
分别配置加载spring的配置类,spring mvc的配置类和拦截路径。
javax.servlet.ServletContainerInitializer
接口的实现类在Servlet3.0环境中,用于配置容器。
Spring中提供上述接口的实现类SpringServletContainerInitializer,它反过来会查找实现WebApplicationInitializer的类,将配置的任务交给他们来完成。
Spring3.2中引入AbstractAnnotationConfigDispatcherServletInitializer就是WebApplicationInitializer的基础实现,所以当部署到servlet3.0容器中时,容器会发现它的子类,并用子类来配置Servlet上下文。
子类中可以重写三个方法:
- getServletMappings():将一个或多个路径映射到DispatcherServlet上;
- getServletConfigClasses():返回的带有@Configuration注解的类用来配置DispatcherServlet;
- getRootConfigClasses():返回的带有@Configuration注解的类用来配置ContextLoaderListener;
DispatcherServlet启动时,创建Spring应用上下文并加载配置文件或配置类中声明的bean;在Spring web应用中,通常还有由ContextLoaderListener创建的另一个上下文。
DispatcherServlet加载包含Web组件的bean,如控制器、视图解析器以及处理器映射;
ContextLoaderListener加载应用中的其它bean,通常指驱动应用后端的中间层和数据层组件。
AbstractAnnotationConfigDispatcherServletInitializer会同时创建DispatcherServlet和ContextLoaderListener。是传统web.xml方式的替代方式。
AbstractAnnotationConfigDispatcherServletInitializer
参考
到上面位置控制器部分已经配置好了,编写控制器:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping(value = "/test")
public String method1(){
return "test ok!";
}
}
控制器部分的启动流程:
spring mybatis配置
控制器部分已经配置完成,查询数据库的内容,使用mybatis持久层。如何通过注解将mybatis与spring整合呢?
@Mapper注解可以代替mapper映射文件,和mybatis-config.xml配置文件,该注解会生成一个静态的SqlSessionFactory,和动态的SqlSession然后调用getMapper()
方法返回mapper对象。使用@Repository将该对象注入到IoC容器中。
pom文件导入必备的依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
在xml配置中持久层两个配置文件mybatis-config.xml和spring-mybatis.xml,两个配置文件所需的关键信息有:
- DataSource对象包括driver,url,username,password;
- SqlSessionFactoryBean对象,其作用是根据DataSource的信息创建静态SqlSessionFactory;
- MapperScannerConfigurer对象,调用SqlSessionFactory动态生成Mapper。
public class MybatisConfig {
// 注入SqlSessionFactoryBean
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// 实体类别名包
bean.setTypeAliasesPackage("com.ssm.pojo");
return bean;
}
//配置mapper映射
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScanner=new MapperScannerConfigurer();
//动态生成mapper的扫描目录
mapperScanner.setBasePackage("com.ssm.dao");
return mapperScanner;
}
}
/** *** */
@Value("${jdbc.driver}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//配置数据源
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setUsername(username);
return dataSource;
}
在根spring配置中需要使用
@Import(MybatisConfig.class)
引入mybatis配置类。DataSource对象既可以配置在spring根容器,也可以通过在mybatis配置类中配置在@Import引入。
到此SSM完全注解开发已经搭建完成。业务部分就正常自动装配Mapper和编写接口就可以了。
四个配置类的主要内容:
SpringContectConfig
import com.ssm.pojo.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.sql.DataSource;
@Configuration
//开启注解扫描的路径
@ComponentScans({
@ComponentScan("com.ssm.pojo"),@ComponentScan("com.ssm.service")}) //组件扫描位置,除控制器扫描所有类
// 加载数据库连接的配置的资源文件
@PropertySource("classpath:datasource.properties")
@Import(MybatisConfig.class)
public class SpringContextConfig{
@Value("${jdbc.driver}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//配置数据源
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setUsername(username);
return dataSource;
}
}
SpringMvcConfig
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
//开启mvc注解扫描
@ComponentScan("com.ssm.controller")
@EnableWebMvc
public class SpringWebmvcConfig implements WebMvcConfigurer {
//释放静态资源
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/../.html").addResourceLocations("/");
registry.addResourceHandler("/../.js").addResourceLocations("/");
registry.addResourceHandler("/../.css").addResourceLocations("/");
registry.addResourceHandler("/../.png").addResourceLocations("/");
} //配置视图解析器,资源管理器,拦截器等
}
MybatisConfig
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatisConfig {
// 注入SqlSessionFactoryBean
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// 实体类别名包
bean.setTypeAliasesPackage("com.ssm.pojo");
return bean;
}
//配置mapper映射
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScanner=new MapperScannerConfigurer();
mapperScanner.setBasePackage("com.ssm.dao");
return mapperScanner;
}
}
配置类和配置文件其实差不多,用相关的对象代替了配置文件,并随web容器初始化。
web.xml的配置类WebConfig
import com.ssm.config.SpringContextConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/** * 该类相当于web.xml主要用来配置DispatcherServlet和加载spring相关的配置类 * 目的是在tomcat启动时加载IoC容器 */
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
//该类随tomcat的启动自动加载
@Override
protected Class<?>[] getRootConfigClasses() {
// 根容器配置类
return new Class[]{
SpringContextConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// web-mvc容器配置类
return new Class[]{
SpringWebmvcConfig.class};
}
@Override
protected String[] getServletMappings() {
// 设置拦截的路径
return new String[]{
"/","*.action"};
}
}
上述对象可能会有所不同,因为存在子类或父类他们都可以完成同样的功能,就像HttpServlet和GenericServlet都可以作为web容器,只是提供的功能数量不同。
所有配置类配置完成后编写测试接口:
```java
@RestController
public class TestController {
@Resource
private TestMapper testMapper;
@GetMapping(value = "/test")
public String method1(){
return "test ok!";
}
@GetMapping(value = "/users")
public List<User> method2(){
List<User> users = testMapper.users();
return users;
}
}
资源中有配置好的完全注解开发的样例,自行下载参考。
边栏推荐
- Which securities company should we choose to open an account for flush stock? Is it safe to open an account with a mobile phone?
- 上半年暂停考试要补考?包含监理工程师、建筑师等十项考试
- 月入1W+的自媒体达人都会用到的运营工具
- "The silk road is in its youth and looks at Fujian" is in the hot collection of works in the Fujian foreign youth short video competition
- 函数基本学习之一
- Design and practice of new generation cloud native database
- burpsuite简单抓包教程[通俗易懂]
- MIT|256KB 内存下的设备上训练
- 编程英语生词笔记本
- 面试题:MySQL的union all和union有什么区别、MySQL有哪几种join方式(阿里面试题)[通俗易懂]
猜你喜欢
[live broadcast review] the first 8 live broadcasts of battle code Pioneer have come to a perfect end. Please look forward to the next one!
按照功能对Boost库进行分类
PMP证书真的有用吗?
九章云极DataCanvas公司蝉联中国机器学习平台市场TOP 3
编程英语生词笔记本
PMP与NPDP之间的区别是什么?
Training on the device with MIT | 256Kb memory
小 P 周刊 Vol.11
Pytest Collection (2) - mode de fonctionnement pytest
MIT|256KB 内存下的设备上训练
随机推荐
BlocProvider 为什么感觉和 Provider 很相似?
"The silk road is in its youth and looks at Fujian" is in the hot collection of works in the Fujian foreign youth short video competition
指标陷阱:IT领导者易犯的七个KPI错误
MySQL series transaction log redo log learning notes
MySQL learning notes - SQL optimization of optimization
locust 系列入门
CNN convolution neural network principle explanation + image recognition application (with source code) [easy to understand]
Pytest collection (2) - pytest operation mode
LIS (longest ascending subsequence) problem that can be understood [easy to understand]
Talking from mlperf: how to lead the next wave of AI accelerator
js数组拼接的四种方法[通俗易懂]
String type conversion BigDecimal, date type
JS how to get a list of elements in a collection object
An operation tool used by we media professionals who earn 1w+ a month
按照功能对Boost库进行分类
地图其他篇总目录
收到一封CTO来信,邀约面试机器学习工程师
测试撤销1
辅音和声母的区别?(声母与辅音的区别)
Several ways of writing main function in C