This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

preface

  • The biggest feature in the Spring framework is that it takes over the life cycle of Java objects. It changes the way we used to build objects.
  • Previously we built objects with new. In Spring we passAutowiredEqual accessbean. This approach has the advantage of not opening up unnecessary memory

Problem description

  • Normally spring will help us find the corresponding bean by injecting the responding class. So that we can conduct business operations.
@RestController
@RequestMapping(value = "/init")
public class InitController {
    private Map<String, Object> resultMap = new HashMap<>();
    @Autowired
    TestService testService;

    public InitController(a) {
        HashMap<String, Object> paramMap = newHashMap<>(); resultMap = testService.getTable(paramMap); }}Copy the code

Problem analysis

  • At first glance, the above code looks fine. Because of ourTestServiceIs a formal Service class. The program is built in Spring at startupInitController“Will passTestServiceCall the method to retrieve the data and store it.
  • But it turned out to be cold storage. The results show a bunch of errors.

  • Based on the stack error message, we can see that it is usTestServiceCauses the null pointer to be abnormal.

  • Why is that? This is where we need to understand spring’s bean building process. When Spring builds a bean, it implements its build through level 3 caching. We’re not going to go into that.
  • Remember that Spring starts by building an object out of New, which is a half-baked bean. The properties are all default values.
  • The property injection of this semi-finished bean is then completed according to the configuration in Spring
  • So whenInitControllerCall the construct regardlessTestServiceIt’s not gonna happen if you’re ready. Because it’s just new InitController. And you use it in the constructorTestServiceSo or throw a null-pointer exception.

conclusion

  • With regard to Spring injection, we need to understand the bean lifecycle to know when to use it and when not to use it.
  • Spring’s level 1 cache is to do semi-finished property injection. Level 2 caching is designed to solve the problem of loop dependency. Level 3 caching is designed to solve the aop aspect problem
  • We will continue to expand the story of Spring’s three-level caching

Come on, work hard