Operation of the database when the project started

For springboot project, the framework provides a variety of interfaces, to perform custom actions when a project starts. Operational scenarios database Benpian record project start-up, use the spring to help us frame packaged JdbcDaoSupport interface is very simple to operate.

 

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;
    }
}

 

Well, the code is shown above. When the project started, it will perform CREATE_TABLE_SQL this sql statement. Also very simple principle, JdbcDaoSupport class implements the spring of InitializingBean interface, and initDao () method is called when the method is performed in afterPropertiesSet ().

 

Here is the relevant source code:

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 {
    }
}

 

 

 

Further, the configuration is as follows:

@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;
    }
}

 

Guess you like

Origin www.cnblogs.com/z-qinfeng/p/11795506.html