Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report