Home > Back-end >  How to inject other instances in springboot abstract class?
How to inject other instances in springboot abstract class?

Time:03-12

Code scenario goes like this:
Abstract class defines an abstract method, different subclasses to override,
But different subclasses are common methods, so will the common method in the abstract class
These common methods use other call other services, so you need to put these services into the abstract,

but now, unable to inject the service class?

Please know that the great god give a solution,

CodePudding user response:

Why can't injection??? Sure is code problem,,,

CodePudding user response:

@ Service (" serviceName ")

The @autowired
@ the Qualifier (" serviceName ")

https://www.cnblogs.com/smileLuckBoy/p/5801678.html

CodePudding user response:

If you want to give a class with other beans, the first thing you will see yourself whether you are registered for this class into a bean, if not run by the spring, and then the spring don't know who to give the injection

CodePudding user response:

Can injection, but not into the abstract class, but into the proxy class a subclass of the abstract class, the subclass must be spring management

CodePudding user response:

A. An abstract class cannot be instantiated, abstract class, therefore, cannot to Spring management, using the @autowired cannot be into other instance, in the method invocation instance must be empty;
2. My solution:
1. Will a subclass of the abstract class to a Spring management, in subclasses into abstract classes need to use an instance of the
2. In the public default implementation methods of an abstract class use reflection to obtain a subclass field instance (injection)

CodePudding user response:

refer to 6th floor Enpong response:
a. Abstract classes cannot be instantiated, abstract class, therefore, cannot to Spring management, using the @autowired cannot be injected other instances, in the method invocation instance must be empty;
2. My solution:
1. Will a subclass of the abstract class to a Spring management, in subclasses into abstract classes need to use an instance of the
2. In the public default implementation methods of an abstract class use reflection to obtain a subclass field instance (injection)


Brother, have the code? My subclass is inherited an abstract class, then a subclass call other methods, were injected class has been empty,

Example:
The abstract class Father {}

The class son extends Father {

The @autowired
Private OtherService service;//there has been a null

Void test () {
The service method ();//it is null, there is an error
}
}

  • Related