spring-how to inject values into static variables

Source: Internet
Author: User
Spring cannot inject a value directly into a static variable because the static variable is not part of the object, it belongs to the class, that is, when the class is loaded with bytecode, the variable is initialized, that is, the variable is allocated memory, which causes spring to ignore the static variable. So this is the wrong way to do this, it is not injected, when the use of the variable will result in a null pointer error:

@Autowiredprivate static StudentMapper studentMapper;

Spring Dependency Injection is dependent on the set method, where static variables do not belong to the object and belong to the class only. The workaround is to add a non-static set method, as follows:

private static StudentMapper studentMapper;public StudentMapper getStudentMapper() {        return studentMapper;}@Autowiredpublic void setStudentMapper(StudentMapper studentMapper) {        this.studentMapper = studentMapper;}

spring-how to inject values into static variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.