Get the App
SLTechnology News&Howtos  ›  Development  › 

How Spring uses @ Autowired to inject dependencies for abstract parent classes

Shulou Source: shulou.com Published: 2022-06-03 09:35:49 11月15日 Update

This article mainly shows you "how Spring uses @ Autowired to inject dependencies for abstract parents". The content is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how Spring uses @ Autowired to inject dependencies into abstract parents".

Sometimes in order to manage or avoid inconsistency, you want the concrete service to inherit the abstract parent class uniformly, while injecting dependencies into the abstract parent class using @ Autowired. Searched the Internet, some solutions are really unflattering, rely on subclasses to inject dependency, what's the point, as follows:

Parent class:

Public abstract class BaseCar {Settings settings;}

When @ Componentpublic class SportsCar extends BaseCar {/ / Autowired modifies the method, determine which class @ Autowired public void (Settings settings) {super.settings=settings;// parent attribute injection} public void print () {System.out.print (settings.getSpeed ());}} according to the method parameter type

It's still called automatic.

After careful study and testing, as long as the attribute to be injected into the parent class is protected protection level, as follows:

Public abstract class BusinessService {@ Lazy @ Autowired protected RedisUtil redisUtil; Logger logger = LoggerFactory.getLogger (this.getClass ();}

After the subclass inherits, you can use redisUtil directly, and there will be no uninjected situation.

That's all of the article "how Spring uses @ Autowired to inject dependencies into abstract parent classes". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Content methods articles subclasses attributes learning help research stop inconsistency parameters at the same time examples situations meaning easy to understand more sometimes organization knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS OPPO Reno vpn Xiaomi Huawei