0

I have a configuration file as such which is creating a bean ,

@Bean
public A a() {
return A.method(x,y,z);
}

In the class A , the constructor seems to be private and the code is as such,

public class A implements SomeInterface () {

@Autowired
private Property property // want this to be autowired 

private A(int x, int y....) { //private constructor
this.x = x;
....
} 

public static method(int x, int y, intz) { //method being called 
return new A (x,y,z...);
}

public static method2(int x,....) {
return new A(x,y...)}


}

When instance of A is created, it is showing property = null. Wondering why property was not autowired even though A is supposedly spring managed. Issue seems to be that it is not even trying to autowire else it should give error related to bean not found or such.

I cannot edit these files since they are libraries but just want to understand why autowiring is not happening. Could it be because of calling the static method for creation?

Denise
  • 898
  • 1
  • 16
  • 30
  • Bean and Autowired field should have same type A != Property – BuruY Apr 15 '21 at 07:19
  • Right.. maybe i should make my question more clear. What I meant was when instance of A is created, it had property set as null – Denise Apr 15 '21 at 07:22
  • That's not possible. You have to pass set the property when you create A – Simon Martinelli Apr 15 '21 at 07:29
  • Autowiring only happens if the instance is created by spring itself. If you create an instance by yourself the annotation is ignored. – Benjamin Schüller Apr 15 '21 at 07:39
  • Ofcourse it will be `null` the autowiring will take place after the object is constructed. So if you look at it after the `a.method(x,yz)` it will still be `null` because Spring hasn't had a change to autowire it. – M. Deinum Apr 15 '21 at 07:51
  • @M.Deinum I was checking in the place where A was being used later on and saw that it had property marked as ```null``` . So dont think spring did autowiring for it at all – Denise Apr 15 '21 at 08:15
  • If the bean is spring managed (as you state in your `@Bean` sample) it will be autowired. Simply put an `@Autowired` field cannot be `null`. If spring cannot wire the dependency it will blow up during startup. So if it is `null` you are either looking at the proxy that is being created due to some AOP, or the `A` that is used isn't injected and SPring managed but retrieved through that `static` method as well. See https://deinum.biz/2020-07-03-Autowired-Field-Null/ for the possible causes. I suspect it isn't the managed instance you think it is. – M. Deinum Apr 15 '21 at 08:34

0 Answers0