前言
近来公司项目进入测试阶段,得以空闲,于是学习了一下spring。虽然我一直从事前端工作,但是学习一下后端的知识总是不错的。
搭建环境
- 开发环境:IntelliJ IDEA
- JDK版本:1.8
- 依赖包管理工具:gradle
- 数据库:MYSQL
正文
工程目录
依赖配置
在工程目录下的build.gradle文件里配置:
dependencies {
compile(group: 'org.springframework',name: 'spring-core',version: '5.2.2.RELEASE')
compile(group: 'org.springframework',name: 'spring-context',version: '5.2.2.RELEASE')
compile(group: 'org.springframework',name: 'spring-beans',version: '5.2.2.RELEASE')
compile(group: 'org.springframework',name: 'spring-aop',version: '5.2.1.RELEASE')
compile(group: 'org.springframework',name: 'spring-web',version: '5.2.2.RELEASE')
compile(group: 'org.springframework',name: 'spring-webmvc',version: '5.2.2.RELEASE')
compile(group: 'org.springframework',name: 'spring-orm',version: '5.2.2.RELEASE')
runtime(group: 'org.springframework',name: 'spring-jdbc',version: '5.2.2.RELEASE')
testCompile(group: 'org.springframework',name: 'spring-test',version: '5.2.2.RELEASE')
compile group: 'org.mybatis', name: 'mybatis', version: '3.5.3'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '2.0.3'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.18'
compile group: 'com.alibaba', name: 'druid', version: '1.1.21'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
compile(group: 'org.slf4j',name: 'slf4j-api',version: '2.0.0-alpha1')
compile(group: 'ch.qos.logback',name: 'logback-core',version: '1.3.0-alpha5')
compile(group: 'ch.qos.logback',name: 'logback-classic',version: '1.3.0-alpha5')
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.6.0-M1'
}
配置servlet
- 创建WebAppInitializer类,代码如下:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootContextConfig.class,DruidDataSourceConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
类WebAppInitializer相当于web.xml,可以继承AbstractAnnotationConfigDispatcherServletInitializer类,也可以实现WebApplicationInitializer接口详情。
RootContextConfig类是与spring相关的配置;DruidDataSourceConfig类是数据库连接配置,这里使用的数据源是阿里的druid;WebMvcConfig类是与试图相关的配置。
- RootContextConfig类
@Configuration
@ComponentScan(basePackages = "org.iris.api",excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {EnableWebMvc.class, RestController.class})})
public class RootContextConfig {
}
- DruidDataSourceConfig类
@Configuration
@PropertySource(value = "classpath:/jdbc/druid.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
@MapperScan(basePackages = "org.iris.api.dao")
public class DruidDataSourceConfig {
@Value("${jdbc.driver}")
private String driverClass;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.user}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.filters}")
private String staticFilter;
@Value("${jdbc.maxActive}")
private int maxActive;
@Value("${jdbc.initialSize}")
private int initialSize;
@Value("${jdbc.maxWait}")
private int maxWait;
@Value("${jdbc.minIdle}")
private int minIdle;
@Value("${jdbc.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${jdbc.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${jdbc.maxOpenPreparedStatements}")
private int maxOpenPreparedStatements;
@Value("${jdbc.testWhileIdle}")
private boolean testWhileIdle;
@Value("${jdbc.testOnBorrow}")
private boolean testOnBorrow;
@Value("${jdbc.testOnReturn}")
private boolean testOnReturn;
@Value("${jdbc.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${jdbc.asyncInit}")
private boolean asyncInit;
@Bean
public DataSource druidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDbType("MYSQL");
dataSource.setDriverClassName(this.driverClass);
dataSource.setUrl(this.jdbcUrl);
dataSource.setUsername(this.userName);
dataSource.setPassword(this.password);
dataSource.setMaxActive(this.maxActive);
dataSource.setInitialSize(this.initialSize);
dataSource.setMaxWait(this.maxWait);
dataSource.setMinIdle(this.minIdle);
dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
dataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
dataSource.setMaxOpenPreparedStatements(this.maxOpenPreparedStatements);
dataSource.setTestWhileIdle(this.testWhileIdle);
dataSource.setTestOnBorrow(this.testOnBorrow);
dataSource.setTestOnReturn(this.testOnReturn);
dataSource.setPoolPreparedStatements(this.poolPreparedStatements);
dataSource.setAsyncInit(this.asyncInit);
try {
dataSource.setFilters(this.staticFilter);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource druidDataSource) throws IOException {
SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactory.setMapperLocations(patternResolver.getResources("classpath*:mapper/*.xml"));
sqlSessionFactory.setDataSource(druidDataSource);
sqlSessionFactory.setTypeAliasesPackage("org.iris.api.pojo");
return sqlSessionFactory;
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(DataSource druidDataSource){
DataSourceTransactionManager manager = new DataSourceTransactionManager();
manager.setDataSource(druidDataSource);
return manager;
}
@Bean
public TransactionInterceptor transactionInterceptor(DataSourceTransactionManager transactionManager){
TransactionInterceptor interceptor = new TransactionInterceptor();
interceptor.setTransactionManager(transactionManager);
Properties porps = new Properties();
porps.setProperty("save*", "PROPAGATION_REQUIRED");
porps.setProperty("del*", "PROPAGATION_REQUIRED");
porps.setProperty("update*", "PROPAGATION_REQUIRED");
porps.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
porps.setProperty("find*", "PROPAGATION_REQUIRED,readOnly");
porps.setProperty("*", "PROPAGATION_REQUIRED");
interceptor.setTransactionAttributes(porps);
return interceptor;
}
}
- druid.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/iris?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT&allowPublicKeyRetrieval=true
jdbc.user=root
jdbc.password=123456
jdbc.filters=stat
jdbc.maxActive=20
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.minIdle=1
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=true
jdbc.maxOpenPreparedStatements=20
jdbc.asyncInit=true
- WebMvcConfig
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.iris.api.controller")
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/views/",".jsp");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}