简体   繁体   中英

Unable to call function of autowired class

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?

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

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