Unable to call function of autowired class

658 Views Asked by At

I have the following classes :

Class 1:

package com.assets;
@Component 
@Scope("request)
public class AssetDetailsImpl implements AssetApi
{
    public void function1(){
    ....
    }

    public void function2(){
    AssetUtil.test1();
    }

}

Class 2:

package com.assets;
@Component 
public class AssetUtil
{
   @Autowired
   AssetDetailsImpl impl;
   //some functions
   public static void test1{
    impl.function1();// NPE I am getting
}

Here my auto wiring not working, its coming null. Both the classes are in the same package. Is it because of the request scope which is there in AssetDetailsImpl? I even tried with @Inject that also was not working. Can anyone please help me to resolve this? Thanks in advance! I have tried removing the scope, but then also the same problem. I have also tried:

AssetUtil(AssetDetailsImpl impl) {
    this.impl = impl;
}

But I am not sure how to deal with the static thing then also how to invoke this constructor?

2

There are 2 best solutions below

0
Simon Martinelli On

The method test1 is static.

But Spring doesn't work with static members because it creates instances of the beans.

Remove static:

public void test1{
    impl.function1();
}

And now you have to make sure that the client of this method is also using autowiring to get an instance of AssetUtil

0
dbreaux On

It looks to me like the issue is that the AssetDetailsImpl Component is Request-scoped, which means it comes and goes with each HTTP request, while the AssetUtil Component which is trying to use it is default-scoped, which is Application/singleton scope.

Personally, I try to use singletons as much as possible. I wouldn't use request scope for the first Component.