持续学习&持续更新中…
守破离
【Java从零到架构师第③季】【38】分模块构建SSM项目
module—parent
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>programmer.lp.ssmdividing</groupId>
<artifactId>SSM_dividing_module</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>dao</module>
<module>service</module>
<module>web</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
module—dao
dao层是数据访问层,是MyBatis干活的地方。
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>SSM_dividing_module</artifactId>
<groupId>programmer.lp.ssmdividing</groupId>
<version>1.0.0</version>
</parent>
<artifactId>dao</artifactId>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
db.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_mybatis?useSSL=false
jdbc.username=root
jdbc.password=root
mybatis.typeAliasesPackage=programmer.lp.domain
mybatis.mapperScanPackage=programmer.lp.dao
mybatis.configLocation=mybatis-config.xml
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
Converter:
public class DateConverter implements Converter<String, Date> {
private Set<String> formats;
public void setFormats(Set<String> formats) {
this.formats = formats;
}
@Override
public Date convert(String dateStr) {
if (null == formats || formats.isEmpty()) return null;
for (String format : formats) {
try {
return new SimpleDateFormat(format).parse(dateStr);
} catch (Exception e) {
System.out.println("不支持:<" + format + ">格式!");
}
}
return null;
}
}
Dao:
public interface SkillDao {
@Insert("INSERT INTO skill(name, level) VALUES(#{name}, #{level})")
@SelectKey(statement = "SELECT LAST_INSERT_ID()",
keyProperty = "id",
keyColumn = "id",
before = false,
resultType = Integer.class)
boolean insert(Skill skill);
@Delete(("DELETE FROM skill WHERE id = #{id}"))
boolean delete(Integer id);
@Update("UPDATE skill SET name = #{name}, level = #{level} WHERE id = #{id}")
boolean update(Skill skill);
@Select("SELECT id, created_time, name, level FROM skill WHERE id = #{id}")
Skill get(Integer id);
@Select("SELECT id, created_time, name, level FROM skill")
List<Skill> list();
}
DaoConfiguration:
@PropertySource("classpath:db.properties")
@MapperScan("${mybatis.mapperScanPackage}")
public class DaoConfiguration {
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${mybatis.typeAliasesPackage}")
private String typeAliasesPackage;
@Value("${mybatis.configLocation}")
private String configLocation;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
Resource location = new ClassPathResource(configLocation);
sqlSessionFactoryBean.setConfigLocation(location);
return sqlSessionFactoryBean;
}
@Bean
public DateConverter dateConverter() {
DateConverter dateConverter = new DateConverter();
Set<String> set = new LinkedHashSet<>();
set.add("yyyy-MM-dd");
set.add("yyyy/MM/dd");
set.add("yyyy年MM月dd日");
dateConverter.setFormats(set);
return dateConverter;
}
}
module—service
service层是业务层,一般需要Spring的事务管理。
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>SSM_dividing_module</artifactId>
<groupId>programmer.lp.ssmdividing</groupId>
<version>1.0.0</version>
</parent>
<artifactId>service</artifactId>
<dependencies>
<dependency>
<groupId>programmer.lp.ssmdividing</groupId>
<artifactId>dao</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
</project>
ServiceConfiguration:
@EnableTransactionManagement
@ComponentScan("programmer.lp.service")
public class ServiceConfiguration {
@Bean
public TransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager manager = new DataSourceTransactionManager();
manager.setDataSource(dataSource);
return manager;
}
}
SkillService:
@Service
@Transactional
public class SkillServiceImpl implements SkillService {
@Autowired
private SkillDao dao;
@Override
public boolean remove(Integer id) {
return dao.delete(id);
}
@Override
public boolean save(Skill skill) {
final Integer skillId = skill.getId();
if (skillId == null || skillId < 1) {
boolean result = dao.insert(skill);
System.out.println(skill.getId());
return result;
}
return dao.update(skill);
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public Skill get(Integer id) {
return dao.get(id);
}
@Transactional(readOnly = true)
@Override
public List<Skill> list() {
return dao.list();
}
}
module—web
web层就是controller层(相当于servlet),是SpringMVC干活的地方。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>SSM_dividing_module</artifactId>
<groupId>programmer.lp.ssmdividing</groupId>
<version>1.0.0</version>
</parent>
<artifactId>web</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>programmer.lp.ssmdividing</groupId>
<artifactId>service</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
WebConfiguration:
@EnableWebMvc
@ComponentScan("programmer.lp.controller")
public class WebConfiguration implements WebMvcConfigurer {
@Autowired
private DateConverter dateConverter;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(dateConverter);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
return resolver;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setDefaultCharset(StandardCharsets.UTF_8);
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.setDefaultCharset(StandardCharsets.UTF_8);
converters.add(stringConverter);
converters.add(jacksonConverter);
}
}
Controller:
@Controller
@RequestMapping("/skill")
public class SkillController {
@Autowired
private SkillService service;
@PostMapping("/remove")
@ResponseBody
public String remove(Integer id) {
return service.remove(id) ? "删除成功" : "删除失败";
}
@PostMapping("/save")
@ResponseBody
public String save(Skill skill) {
return service.save(skill) ? "保存成功" : "保存失败";
}
@GetMapping("/get")
@ResponseBody
public Skill get(Integer id) {
return service.get(id);
}
@GetMapping("/list")
@ResponseBody
public List<Skill> list() {
return service.list();
}
}
Initializer:
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{DaoConfiguration.class, ServiceConfiguration.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
FilterRegistration.Dynamic encodingFilter =
servletContext.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
encodingFilter.setInitParameter("encoding", "UTF-8");
encodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
}
参考
小码哥-李明杰: Java从0到架构师③进阶互联网架构师.
本文完,感谢您的关注支持!
|