I am using spring boot 2.5.2 and java 11 with JDBC to connect with MSSQL
But I want to lazy load the JDBCTemplate bean with @Lazy annotation
It is not loading lazily Can someone help?
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));
}
}
This is my config file and bean serbMsSqlJdbcTemplate is included in a constructor where I have also used @Lazy annotation
public StranDao(@Qualifier("serbMsSqlJdbcTemplate") @Lazy JdbcTemplate serbTemplate) {
this.serbTemplate = serbTemplate;
}
but it is not working
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html
May be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.
Did you try to put it on the class and not on the beans?
Did you also try to use it through the bean? like this: