Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inject same class using Spring?

Tags:

java

spring

I have a class say UserService which implements Service and annotated with Service StereoType, I'm using Spring AOP and want to do temporary workaround for this(I know this can be done in better way)

@Service
public class UserService implements Service{
   @Autowired
   private Service self;
}

I tried this but got BeanNotFoundException, did I missed anything?

I know I have to go with AspectJ with @Configurable but just looking for little temporary workaround

like image 719
Premraj Avatar asked Sep 08 '25 17:09

Premraj


1 Answers

Why on earth would you need to do this? In any method where you need to refer to the current instance, ie self you simply use the this keyword.

Are we missing something? If there's something else you're trying to do, try to clarify your question and we'll take a stab at it.

In case you're wondering, this doesn't work because the bean can't be injected until it has been fully constructed --> this means that Spring has to have injected all properties of the bean. Effectively what you've done is created a circular dependency because Spring tries to instantiate the bean and when it does, it discovers that it needs to Autowire another bean. When it tries to find that bean it can't because the bean hasn't been added to the list of initialized beans (because it's currently being initialized). Does that make sense? This is why you get the BeanNotFoundException because the bean can't be initialized.

like image 85
Chris Thompson Avatar answered Sep 10 '25 06:09

Chris Thompson