2

I wrote a small spring boot program that needs to connect to a database by using jdbcTemplate. The JDBC driver is present and I set everything in application.properties:

spring.datasource.url=jdbc:oracle:thin:@servername:1521:foo
spring.datasource.username=guesswho
spring.datasource.password=iwonttell
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

When I let spring boot actuator display the beans by opening localhost:8080/beans I can see my class that needs the bean ...

1:Object
bean:"mybean"
scope:"singleton"
type:"de...."
resource:"file [C:/....class]"
dependencies:Array[1]
0:"jdbcTemplate"

... and I can see the bean was defined:

56:Object
bean:"jdbcTemplate"
scope:"singleton"
type:"org.springframework.jdbc.core.JdbcTemplate"
resource:"class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$JdbcTemplateConfiguration.class]"
dependencies:Array[0]

This is my code which shows all three variants of autowiring I tried and none of them works

public class myBean implements IMyBean {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Autowired
  public myBean(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Autowired
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public foo searchDb(String for) {
    String sql = "SELECT bar FROM ...";

    jdbcTemplate.query( sql, ...

In the last line with jdbcTemplate.query a NPE occurs.

I think I'm unable to see the forrest for the trees. I checked the suggested answers stackoverflow provides (e.g. spring-boot properties not @Autowired) but I think they don't match my problem. Help is wholeheartedly appreciated ...

Community
  • 1
  • 1
Marged
  • 10,577
  • 10
  • 57
  • 99

1 Answers1

1

The problem was caused by a forgotten annotation: @AutoWired was missing and because of this I had two instances. One was configured correctly and included the jdbcTemplate, the other had a null jdbcTemplate. I checked the first one, but it was not used.

Marged
  • 10,577
  • 10
  • 57
  • 99