0

Im new to spring and Jdbc, JdbcTemplate works when I auto wire it in the main class, but when I auto wire it in any other class it is null.

note: I comment out one of the JdbcTemplate when I test the other, I thought it might make a conflict.

Test class (Main)

@SpringBootApplication
public class Test implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;  // this works

    public static void main(String[] args) {
        SpringApplication.run(Test.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        System.out.println("main class jdbc template = "+jdbcTemplate);

    }
}

StudentDaoImpl class

    public class StudentDaoImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate; //this is null

}

Application.properties

spring.datasource.url=jdbc:mysql://localhost/db
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

I really have no clue why is this happening, any help will be appreciated.

sultanduwaik
  • 11
  • 1
  • 4

1 Answers1

0

Are you creating the StudentDaoImpl class yourself?

StudentDaoImpl dao = new StudentDaoImpl()?

If not, then annotate your StudentDaoImpl class with @Repository so it will be automatically picked up by Springs component scanning.

If yes then you have to set the JdbcTemplate yourself (in this case via a setter)

Note: Autowiring doesn’t work when you create an instance yourselves with the new keyword.

MevlütÖzdemir
  • 3,180
  • 1
  • 23
  • 28