基于springboot实现自定义的start启动类

本文的目标是通过springboot提供的支持,使用户在springboot项目中导入我们的依赖就可以自动注入bean实现功能,本次以自定义的DbHelper为例,一个简化jdbc操作的简单程序

1.主配置类

首先使用@Configuration定义为配置类

然后使用@EnableConfigurationProperties({DbProperties.class}),加载配置文件中的属性,这个类后面会给出

然后加上条件注解,表面只有存在DbProperties这个类时才加载这个

@Configuration
@EnableConfigurationProperties({DbProperties.class})
@ConditionalOnClass({ DbProperties.class})
public class SystemInfoAutoConfiguration {
    /**
     * 按条件加载Dbhelper,如果没用数据库驱动则不加载
     */
    @Bean
    @ConditionalOnClass(name="com.mysql.cj.jdbc.Driver")
    public DBHelper dbHelper() {
        System.out.println("加载了DBHelper");
        return new DBHelper();
    }
}

2.读取配置文件的属性

这里使用的注解的功能时获取配置文件为yc.db的属性

比如用户可以设置url为yc.db.url,以此类推

@ConfigurationProperties(prefix = "yc.db")
public class DbProperties{
    String url;
    String uname;
    String pwd;
    String driver;

3.DbHelper实现

这里首先就是加载属性,获取数据库连接,并且实现了一个查询方法,传入数据实体类,sql语句和具体参数进行查询

public class DBHelper {

    @Autowired
    private DbProperties dbProperties;
    //获取一个Connection
    public Connection getConnection(   ) throws SQLException {
        System.out.println(dbProperties);
        try{
            Class.forName(dbProperties.getDriver());
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }
        return DriverManager.getConnection( dbProperties.getUrl(), dbProperties.getUname(), dbProperties.getPwd());
    }
    
public <T> List<T> select(Class<T> c, String sql, Object... params) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        List<T> result = new ArrayList<>();
        List<Map<String, Object>> list = this.select(sql, params);

        for (Map<String, Object> map : list) {
            T t = null; // 使用更通用的方式创建实例
            try {
                t = c.getDeclaredConstructor().newInstance();
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }

            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                // 处理属性名
                String methodName = "set" + Character.toUpperCase(key.charAt(0)) + key.substring(1);

                try {
                    Method setMethod = c.getMethod(methodName, value.getClass());
                    setMethod.invoke(t, value); // 使用反射动态调用 set 方法
                } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
                    // 处理异常情况
                    e.printStackTrace(); // 可以根据具体情况选择如何处理异常
                }
            }

            result.add(t);
        }
        return result;
    }
}

4.利用spi机制加载主配置类

在这个目录下创建指定的文件

文件名为org.springframework.boot.autoconfigure.AutoConfiguration.imports

里面写上要加载的主配置类的位置比如

com.yc.SystemInfoAutoConfiguration

对于springboot的源码中也是这么实现加载的

5.打包部署

记得导入依赖先,这里主要是自动配置的依赖和springboot的父依赖,并且记住打包后的名字

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <scope>compile</scope>
    </dependency>

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.2</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <groupId>com.yc</groupId>
  <artifactId>dbhelper_start</artifactId>
  <version>1.0.1</version>
  <packaging>jar</packaging>

在maven工具的生命周期中选择install,等待打包完成

5.测试

在springboot项目中导入依赖,这里是此项目的依赖以及mysql的连接依赖

        <dependency>
            <groupId>com.yc</groupId>
            <artifactId>dbhelper_start</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>

写好测试的类,这里使用controller层中写一个访问的方法

@RestController
public class MyDb {
    @Autowired
    private DBHelper db;
    @RequestMapping("/")
    public String index() {
        String sql = "select * from user";
        List<User> users;
        try {
            users = db.select(User.class, sql);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return "Hello World!" + users;
    }
}

配置文件中要加入相关配置,端口改成80可以不用输入端口号,因为浏览器默认端口为80,所以

只要启动后在浏览器中输入localhost就可以看到结果

server:
  port: 80
yc:
  db:
    url: jdbc:mysql://localhost:3306/myuser
    uname: yourname
    pwd: yourpwd
    driver: com.mysql.cj.jdbc.Driver

结果,查询数据成功

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot是Java语言的一种开放源代码框架,可以快速构建基于Spring框架的Web应用程序。而mybatis-plus是基于mybatis的增强工具,可以进一步简化mybatis的使用,提高开发效率。 定时器管理是指定时执行某些任务,比如定时清理缓存、定时备份数据库等。在SpringBoot中,可以使用@Scheduled注解来实现定时任务。而基于mybatis-plus的定时器管理,可以通过创建一个定时任务执行器的实体类,并使用mybatis-plus提供的BaseMapper进行数据库操作。 下面是一个简单的示例: 1. 创建一个定时任务执行器的实体类,例如: ```java @Data @TableName("t_schedule_task") public class ScheduleTaskEntity { @TableId(type = IdType.AUTO) private Long id; @TableField("job_name") private String jobName; @TableField("cron_expression") private String cronExpression; @TableField("job_class") private String jobClass; @TableField("job_group") private String jobGroup; @TableField("job_status") private Boolean jobStatus; @TableField("job_data") private String jobData; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; } ``` 2. 创建一个Mapper接口,继承mybatis-plus提供的BaseMapper,并实现一些自定义的数据库操作方法,例如: ```java public interface ScheduleTaskMapper extends BaseMapper<ScheduleTaskEntity> { List<ScheduleTaskEntity> selectByJobStatus(Boolean jobStatus); void updateByJobName(@Param("jobName") String jobName, @Param("jobStatus") Boolean jobStatus); } ``` 3. 创建一个定时任务的执行类,例如: ```java @Component public class ScheduleTaskExecutor { @Autowired private ScheduleTaskMapper scheduleTaskMapper; @Scheduled(cron = "0/5 * * * * ?") public void executeTask() { List<ScheduleTaskEntity> taskList = scheduleTaskMapper.selectByJobStatus(true); for (ScheduleTaskEntity task : taskList) { String jobName = task.getJobName(); String jobClass = task.getJobClass(); String jobGroup = task.getJobGroup(); String jobData = task.getJobData(); try { Class<?> clazz = Class.forName(jobClass); JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(jobName, jobGroup).build(); if (StringUtils.isNotBlank(jobData)) { jobDetail.getJobDataMap().put("jobData", jobData); } Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).build(); Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } catch (Exception e) { e.printStackTrace(); } scheduleTaskMapper.updateByJobName(jobName, false); } } } ``` 4. 在配置文件中配置数据库连接信息、mybatis-plus和定时任务的属性,例如: ```yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root mybatis-plus: mapper-locations: classpath:/mapper/**/*.xml configuration: map-underscore-to-camel-case: true spring: task: scheduling: pool: size: 10 scheduler: pool-size: 100 ``` 5. 在启动类上加上@EnableScheduling注解,启动应用程序即可。 通过以上步骤,就可以基于mybatis-plus实现定时器管理。当数据库中的定时任务状态为true时,定时任务执行器会根据任务的cron表达式自动执行任务,并将任务状态更新为false,以避免重复执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值