项目启动时操作数据库

对于springboot项目而言,框架提供了多种接口,在项目启动时执行自定义操作。本篇记录项目启动时操作数据库的场景,利用了spring框架帮我们封装好的JdbcDaoSupport接口,操作起来还是很简单的。

application.properties

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://120.79.xx.yy:3306/security?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
spring.datasource.username = root
spring.datasource.password = 132123
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class DefaultDaoSupport extends JdbcDaoSupport{

    public static final String CREATE_TABLE_SQL = "create table if not exists tb_student (id bigint(20) NOT NULL AUTO_INCREMENT," +
            "username varchar(64) not null, " +
            "age bigint(20) , PRIMARY KEY (id))";

    @Override
    protected void initDao() throws Exception {
        super.getJdbcTemplate().execute(CREATE_TABLE_SQL);
    }
}
@SpringBootConfiguration
public class InitConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public DaoSupport daoSupport() {
        DefaultDaoSupport defaultDaoSupport = new DefaultDaoSupport();
        defaultDaoSupport.setDataSource(dataSource);
        return defaultDaoSupport;
    }
}

好, 代码就是如上所示。 项目启动时,就会执行 CREATE_TABLE_SQL 这条sql语句。 原理也很简单,JdbcDaoSupport 类实现了spring的InitializingBean接口,而initDao()方法在afterPropertiesSet() 方法执行时调用。

下面是相关源码:

public abstract class DaoSupport implements InitializingBean {
    protected final Log logger = LogFactory.getLog(this.getClass());

    public DaoSupport() {
    }

    public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
        this.checkDaoConfig();

        try {
            this.initDao();
        } catch (Exception var2) {
            throw new BeanInitializationException("Initialization of DAO failed", var2);
        }
    }

    protected abstract void checkDaoConfig() throws IllegalArgumentException;

    protected void initDao() throws Exception {
    }
}

另外,配置如下所示:

@SpringBootConfiguration
public class InitConfig {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Bean
    public DaoSupport daoSupport() {
        DefaultDaoSupport defaultDaoSupport = new DefaultDaoSupport();
//        defaultDaoSupport.setDataSource(dataSource);
        defaultDaoSupport.setJdbcTemplate(jdbcTemplate);
        return defaultDaoSupport;
    }
}

猜你喜欢

转载自www.cnblogs.com/z-qinfeng/p/11795506.html