對於springboot項目而言,框架提供了多種接口,在項目啓動時執行自定義操做。本篇記錄項目啓動時操做數據庫的場景,利用了spring框架幫咱們封裝好的JdbcDaoSupport接口,操做起來仍是很簡單的。mysql
application.propertiesspring
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() 方法執行時調用。sql
下面是相關源碼:數據庫
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 { } }
另外,配置以下所示:springboot
@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; } }