Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor-Injected field is null in Spring CGLIB enhanced bean

Tags:

java

spring

I have this repository:

@Repository
public class MyRepository {

  private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

  public MyRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
    this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
  }

  void doSomething() {
    namedParameterJdbcTemplate.update(...);
  }
}

Which worked as expected with Spring Boot 1.4.5 (Spring Core & JDBC 4.3.7). When debugging doSomething(), I can see that the instance of MyRepository is an ordinary object and the namedParameterJdbcTemplate is set.

However, as soon as I update to Spring Boot 1.4.6 (Spring Core & JDBC 4.3.8) or higher, the instance of MyRepository is a MyRepository$$EnhancerBySpringCGLIB and namedParameterJdbcTemplate is null. I see it being injected in the constructor, however, at that point my repository is not yet CGLIB enhanced.

Why is that? I couldn't find a hint in the release 4.3.8 release notes.

like image 238
Michel Jung Avatar asked Sep 15 '25 15:09

Michel Jung


2 Answers

I had something related. My methods were final and because of this, Spring was using CGLIB Proxied Classes instead of the default behavior (Spring AOP Proxied Classes). So to access the class properties, I had to call the getXXX() method, otherwise, the property would be returned null every time I've tried to access it.

like image 91
Felipe Desiderati Avatar answered Sep 17 '25 04:09

Felipe Desiderati


I had a similar problem... I fixed my case by changing method to public instead of protected.

Have you tried

@Repository
public class MyRepository {

  private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

  public MyRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
    this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
  }

  public void doSomething() {
    namedParameterJdbcTemplate.update(...);
  }
}
like image 41
Sander Ruul Avatar answered Sep 17 '25 03:09

Sander Ruul