I find it hard to understand why something in Spring's Java configuration using @Autowired does not work.
First, I'm trying to move all my @Autowired annotations to Java Config classes. This causes my "POJOs" to return to real POJOs. Then, I can not only easily test them outside the context of Spring, but also easily and easily use mock objects.
So I first tried this:
@Configuration public class Module3ConfigClass { @Autowired private Module1Bean1 module1Bean1; @Autowired private Module2Bean1 module2Bean1; @Bean public Module3Bean1 module3Bean1() { return new Module3Bean1(module1Bean1, module2Bean1); } }
However, when the Module3Bean1 constructor is Module3Bean1 , both passed to Beans are zero. If you do not follow the naming convention above, both of these Beans will be created in a separate Java configuration file. Also note that everything is connected correctly - I know this, because everything works fine when the @Autowired tags are in the corresponding fields of the private member inside Module3Bean1 .
FWIW, I tried adding the @DependsOn annotation to the module3Bean1() method, but had the same results. I think I just wanted to understand this behavior, is it correct (I suspect this is so, but why)?
Finally, I found an acceptable workaround shown here:
@Configuration public class Module3ConfigClass { @Bean @Autowired public Module3Bean1 module3Bean1(Module1Bean1 module1Bean1, Module2Bean1 module2Bean1) { return new Module3Bean1(module1Bean1, module2Bean1); } }
It seems wonderful to me, but if someone wants to comment on it, that would be welcome too.
source share