0

I have following classes :

Class 1

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

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

}

Class 2

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

here my autowiring not working, its coming null. both the classes in 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!

Edit : I have tried removing the scope, but then also the same problem.

Tech Geek
  • 437
  • 1
  • 4
  • 19
  • A few pointers. Firstly, try to inject the dependency using a constructor injection. This will potentially reveal problems that field injection tends to hide. Secondly, why is our bean scope for `request`? – akortex Jul 30 '21 at 07:57
  • @tgdavies yes i tried, seems not workin – Tech Geek Jul 30 '21 at 08:10
  • @akortex my I tried removing scope but then also didnt work. Also I tried making through constructor : AssetDetailsImpl impl = new AssetDetailsImpl(); that was also coming null – Tech Geek Jul 30 '21 at 08:42

1 Answers1

0

Class 2 need a constructor like this to work:

AssetUtil(AssetDetailsImpl impl) {
    this.impl = impl;
}
  • Ok, so how this constructor will be invoked ? as from detailsImpl class I am calling new AssetUtil().test1(); – Tech Geek Jul 30 '21 at 10:06
  • 1
    @TechGeek: if you do `new AssetUtil()` then **no** dependency injection of any kind will happen, you're using it wrong. – Joachim Sauer Jul 30 '21 at 10:08
  • @JoachimSauer I made it static and called it with classname, but then also its not working. Then how should I use it? – Tech Geek Jul 30 '21 at 11:37
  • @TechGeek: for Spring to be able to inject stuff, it needs to have touched it. In other words: inject the `AssetUtil` into your classes or otherwise request it from Spring. – Joachim Sauer Jul 30 '21 at 13:16