Springboot初始化加载数据的方法

1、使用@PostConstruct注解

@PostConstruct
public void postConstructDemo(){
	// 执行相关业务
	System.out.println("PostConstruct初始化数据");
}

2、实现InitializingBean接口

@Component
public class InitializingBeanDemo implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        // 执行相关业务
        System.out.println("InitializingBeanDemo初始化数据");
    }
}

3、使用@Bean注解的initMethod执行初始化方法

@Bean(initMethod = "init")
public InitMethodDemo initMethodTest(){
	return new InitMethodDemo();
}

public class InitMethodDemo {

    public void init(){
        // 执行相关业务
        System.out.println("InitMethodDemo初始化数据");
    }

}

4、实现CommandLineRunner 接口

@Component
public class CommandLineRunnerDemo implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 执行相关业务
        System.out.println("CommandLineRunnerDemo初始化数据");
    }
}

5、实现ApplicationRunner 接口

@Component
public class ApplicationRunnerDemo implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 执行相关业务
        System.out.println("ApplicationRunnerDemo初始化数据");
    }
}

6、实现ApplicationListener接口

@Component
public class ApplicationListenerDemo implements ApplicationListener<ApplicationStartedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        // 执行相关业务
        System.out.println("ApplicationListenerDemo初始化数据");
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}

持续更新中...

Springboot是一个非常流行的开源框架,它可以大幅度简化在Java Web应用中的开发流程。在Springboot中,我们可以使用JDBC来连接数据库。但是,我们在使用JDBC时常常会遇到数据库连接池的问题,因为每一次连接都需要连接池,而连接池是需要初始化的,这样会严重影响系统的性能。为了解决这个问题,Springboot提供了权限定的数据源(Datasource)及加载数据源的自动配置,这样我们就可以避免手动管理数据源,而只需要在配置文件中定义数据源即可,Springboot会在运行时自动加载配置。 在Springboot中,数据源的配置通常放在application.properties或application.yml文件中。我们可以使用以下配置来配置数据源: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=admin ``` 在配置数据源后,我们需要使用注解让Springboot自动加载数据源。在Springboot中,我们可以使用`@EnableAutoConfiguration`注解来启用自动配置,这个注解会自动配置所有支持的特性,比如数据源、缓存、MVC、JPA等等。我们也可以使用`@ComponentScan`注解指定要扫描的包,而不是让Springboot自动扫描。 综上所述,Springboot可以非常方便地加载数据源。通过在配置文件中定义数据源,再使用注解让Springboot自动加载,我们可以避免手动管理连接池,从而提高系统的性能。如果您正在开发Java Web应用,Springboot是一个非常不错的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangjia_happy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值