今天总结下SpringBoot 封装组件的几种方式,第一种:基于application.properties 配置文件+spring 注解标签方式,实现相关组件的封装:
任务要求:常用SQL 脚本方式完成定时任务的建表、查询、新增、修改和删除的功能操作,同时封装为组件,方便其他业务模块的调用。
核心代码如下:
第一:功能组件的相关配置参数:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class CronTaskConfigEntity {
// cron 数据库url 地址
@Value("${com.ucas.cron.database.url}")
private String url;
// cron 数据库用户名称
@Value("${com.ucas.cron.database.username}")
private String username;
// cron 数据库密码
@Value("${com.ucas.cron.database.password}")
private String password;
// cron 数据库驱动
@Value("${com.ucas.cron.database.driverClassName}")
private String driverClassName;
// set 和 get 方法
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
}
第二:实列化对象:
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class CronTask implements Serializable{
private Long id;
private String task_name;
private String cron;
private String class_name;
private String method_name;
private Integer type_;
private Integer state_;
private String remark_;
private String created_by;
private Date created_dt;
// set 和 get 方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public String getClass_name() {
return class_name;
}
public void setClass_name(String class_name) {
this.class_name = class_name;
}
public String getMethod_name() {
return method_name;
}
public void setMethod_name(String method_name) {
this.method_name = method_name;
}
public Integer getType_() {
return type_;
}
public void setType_(Integer type_) {
this.type_ = type_;
}
public Integer getState_() {
return state_;
}
public void setState_(Integer state_) {
this.state_ = state_;
}
public String getRemark_() {
return remark_;
}
public void setRemark_(String remark_) {
this.remark_ = remark_;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_dt() {
return created_dt;
}
public void setCreated_dt(Date created_dt) {
this.created_dt = created_dt;
}
}
三、查询字段与实体对象转换。
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.ucas.cron.domain.CronTask;
public class CronTaskMapper implements RowMapper<CronTask> {
@Override
public CronTask mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
CronTask object = new CronTask();
object.setId(rs.getLong("id"));
object.setClass_name(rs.getString("class_name"));
object.setCron(rs.getString("cron"));
object.setMethod_name(rs.getString("method_name"));
object.setRemark_(rs.getString("remark_"));
object.setState_(rs.getInt("state_"));
object.setTask_name(rs.getString("task_name"));
object.setType_(rs.getInt("type_"));
return object;
}
}
四、定时任务工具类:基于springboot jdbc
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import com.ucas.cron.domain.CronTask;
import com.ucas.cron.mapper.CronTaskMapper;
/**
* cron 工具类封装
*
* @author zzg
*
*/
public class CronTaskUtil {
private JdbcTemplate template;
// set 和 get 方法
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
// 表sql是否存在
String tableName = "sys_cron";
// 建表sql
String create = "create table sys_cron (" + " id bigint(15) not null comment '主键',"
+ " task_name varchar(128) comment '任务名称'," + " cron varchar(64) comment '时间规则',"
+ " class_name varchar(64) comment '类名'," + " method_name varchar(64) comment '方法名称',"
+ " type_ tinyint(4) comment '任务类型:1:系统初始化 2:自定义'," + " state_ tinyint(4) comment '状态: 1:启用,2:禁用',"
+ " remark_ varchar(64) comment '备注'," + " created_by varchar(64) comment '创建人',"
+ " created_dt datetime comment '创建时间'," + " primary key (id)" + " )";
// 新增sql
String insert = "insert into sys_cron(id, task_name, cron, class_name, method_name, type_, state_, remark_) values (?,?,?,?,?,?,?,?)";
// 删除sql
String delete = "delete from sys_cron where id = ?";
// 更新sql
String update = "update sys_cron set state_ = ? where id = ?";
// 查询sql
String select = "select id, task_name, cron, class_name, method_name, type_, state_, remark_ from sys_cron";
/**
* sys_cron 初始化方法
*
* @return
* @throws SQLException
*/
public boolean init() throws SQLException {
Connection conn = template.getDataSource().getConnection();
ResultSet tabs = null;
try {
DatabaseMetaData dbMetaData = conn.getMetaData();
String[] types = { "TABLE" };
tabs = dbMetaData.getTables(null, null, tableName, types);
if (tabs.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
tabs.close();
conn.close();
}
return false;
}
/**
* sys_cron 插入
*
* @param entity
* @throws SQLException
*/
public void insert(CronTask entity) throws SQLException {
if (!init()) {
template.execute(create);
}
template.update(insert, entity.getId(), entity.getTask_name(), entity.getCron(), entity.getClass_name(),
entity.getMethod_name(), entity.getType_(), entity.getState_(), entity.getRemark_());
}
/**
* sys_cron 删除
*
* @param entity
*/
public void delete(String id) {
template.update(delete, id);
}
/**
* sys_cron 更新
*/
public void update(Integer state, Long id) {
template.update(update, state, id);
}
/**
* sys_cron 查询
*
* @throws SQLException
*/
public List<CronTask> select() throws SQLException {
if (!init()) {
template.execute(create);
}
List<CronTask> list = template.query(select, new CronTaskMapper());
return list;
}
}
五、springboot 配置对象,实现化自定义工具类对象:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.ucas.cron.config.domain.CronTaskConfigEntity;
import com.ucas.cron.util.CronTaskUtil;
@Configuration
public class CronTaskConfig {
@Autowired
private CronTaskConfigEntity config;
/**
* DataSource
* @return
*/
public DriverManagerDataSource getDataSources(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(config.getDriverClassName());
dataSource.setUrl(config.getUrl());
dataSource.setUsername(config.getUsername());
dataSource.setPassword(config.getPassword());
return dataSource;
}
/**
* JdbcTemplate
* @return
*/
public JdbcTemplate getJdbcTemplates(){
JdbcTemplate template = new JdbcTemplate(getDataSources());
return template;
}
/**
* CronTaskUtil
* @return
*/
@Bean(name = "cronTaskUtil")
public CronTaskUtil getCronTaskUtil(){
CronTaskUtil util = new CronTaskUtil();
util.setTemplate(getJdbcTemplates());
return util;
}
}
自此,组件的相关功能编码已经全部完成。
将改组件模块打包成jar 包,方便业务模块的调用。
通用war 设计图:
公共依赖的pom.xml 文件:
<!-- 集中定义管理依赖版本号 -->
<properties>
<spring.version>4.3.21.RELEASE</spring.version>
<commons-lang.version>2.6</commons-lang.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-net.version>3.6</commons-net.version>
<commons-io.version>2.6</commons-io.version>
<commons-collections.version>3.2.1</commons-collections.version>
<servlet-api.version>3.1.0</servlet-api.version>
<fastjson.version>1.2.48</fastjson.version>
<oshi-core.version>3.9.1</oshi-core.version>
<mysql-connector-java.version>8.0.11</mysql-connector-java.version>
<spring-data-redis.version>2.1.2.RELEASE</spring-data-redis.version>
<jedis.version>3.0.1</jedis.version>
</properties>
<!--digipower core 核心jar 包依赖 -->
<dependencies>
<!--spring IOC 功能 -->
<!--spring-core 核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-context 全局IOC容器 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-context-support 拓展 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-beans Bean注册 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-experession EL表达式 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring AOP 功能 -->
<!-- 集成spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring JDBC 功能 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring web功能 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql 数据库驱动jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!--集成AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!--common-lang 常用工具包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<!--commons-lang3 工具包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!--commons-codec 加密工具包 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!--commons-net 网络工具包 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>${commons-net.version}</version>
</dependency>
<!--common-io 工具包 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--common-collection 工具包 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<!-- 集成servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--windows 系统性能监控依赖jar -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>${oshi-core.version}</version>
</dependency>
<!-- redis 功能模块集成 -->
<!-- redis-spring适配器 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis.version}</version>
</dependency>
<!--redis客户端 依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>commmon-base</module>
<module>common-component</module>
</modules>
在相关业务模块的pom.xml 中添加改组件
<dependency>
<groupId>com.***</groupId>
<artifactId>****-common-cron</artifactId>
<version>${project.version}</version>
</dependency>
在业务模块中配置文件中application.properties添加改组件初始化参数:
# cron 数据库配置
com.***.ucas.cron.database.url=jdbc:mysql://192.168.1.***:3306/***?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
com.***.ucas.cron.database.username=root
com.***.ucas.cron.database.password=***
com.***.ucas.cron.database.driverClassName=com.mysql.cj.jdbc.Driver