简体   繁体   中英

Can I inject same class using 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

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.

You can edit your class to be

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.INTERFACES)
public class UserService implements Service
{
    @Autowired
    private Service self;
}

this should work

I know this isn't quite answering the question, but I'd suggest re-writing your code so that you do not need to rely on aspects being applied to the self-invocation. For example, if you have some transactional method, just make sure that the transaction stuff gets properly setup in the calling method.

If you really need to, you could make your class ApplicationContextAware and fetch the bean-with-aspects from the context

This works fine -

@Service(value = "someService")
public class UserService implements Service{
   @Resource(name = "someService")
   private Service self;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM