SpringBoot 中使用 JDBC 进行延迟加载

问题描述 投票:0回答:1

我正在使用

spring boot 2.5.2
java 11
与 JDBC 来连接 MSSQL 但我想使用 @Lazy 注释来延迟加载 JDBCTemplate bean

它没有延迟加载 有人可以帮忙吗?

import lombok.extern.slf4j.Slf4j;
import net.media.strategyconfig.models.SemArbConfigDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@EnableConfigurationProperties(SerbConfigDetails.class)
@Configuration
@Slf4j
public class DBConfig {

    @Lazy
    @RefreshScope
    @Bean
    public DataSource semArbDataSource(SerbConfigDetails serbDetails) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        log.info("Hii");
        dataSource.setDriverClassName(semArbDetails.getDriverClassName());
        dataSource.setUrl(semArbDetails.getJdbcUrl());
        dataSource.setUsername(semArbDetails.getUsername());
        dataSource.setPassword(semArbDetails.getPassword());
        return dataSource;
    }

    @Lazy
    @RefreshScope
    @Bean
    public JdbcTemplate serbMsSqlJdbcTemplate(SerbConfigDetails serbDetails) {
        log.info("Hii 2");
        return new JdbcTemplate(semArbDataSource(serbDetails));
    }
}

这是我的配置文件和 bean

serbMsSqlJdbcTemplate
包含在构造函数中,我还使用了
@Lazy
注释

public StranDao(@Qualifier("serbMsSqlJdbcTemplate") @Lazy JdbcTemplate serbTemplate) {
    this.serbTemplate = serbTemplate;
}

但它不起作用

java spring-boot spring-jdbc spring-data-jdbc
1个回答
0
投票

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html

可用于直接或间接用@Component注释的任何类或用@Bean注释的方法。

您是否尝试将其放在课堂上而不是豆子上?

© www.soinside.com 2019 - 2024. All rights reserved.