Why can't the Bean's set method be static type when spring is injected?

Source: Internet
Author: User

A static method belongs to the class, and the normal method belongs to the entity object (that is, the new object), and spring injection is the instantiation of the object in the container, so the static method cannot be used
In Springframework, we cannot @autowired a static variable to make it a spring bean, such as the following:
[Java]
    1. @Autowired
    2. Private static YourClass YourClass;


Can try, yourclass in this state can not be dependent injection, will throw run-time exception java.lang.NullPointerException, why? The static variable/class variable is not an object's property, but a property of a class. Spring is based on dependency injection at the object level.

Static variables/class variables are used to extend the use of static methods. Static methods are not recommended in spring. The primary purpose of dependency injection is to allow the container to produce an instance of an object, and then use them throughout the life cycle, while also making testing easier to work with.

Once you use static methods, it is no longer necessary to produce instances of this class, which makes testing more difficult, and you cannot generate multiple instances of different dependent environments for a given class, depending on the injection method. This static field is implicitly shared, And is a global state, and spring does not recommend it.

Why can't the Bean's set method be static type when spring is injected?

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.