Note that there are some explanatory texts on larger screens.

plurals
  1. POSpring Java Config using Autowired caused NPE
    primarykey
    data
    text
    <p>I am having difficulty understanding why something in Spring Java Config using <code>@Autowired</code> does not work.</p> <p>First, I am trying to move all my <code>@Autowired</code> annotations in the Java Config classes. This has the effect of making my "POJOs" back into real POJOs. I can then not only test them easily outside of a Spring context, but can also use mock objects easily and readily.</p> <p>So I first tried this:</p> <pre><code>@Configuration public class Module3ConfigClass { @Autowired private Module1Bean1 module1Bean1; @Autowired private Module2Bean1 module2Bean1; @Bean public Module3Bean1 module3Bean1() { return new Module3Bean1(module1Bean1, module2Bean1); } } </code></pre> <p>However, when the <code>Module3Bean1</code> constructor is invoked, both passed in Beans are null. If you didn't follow my made up naming convention above, both of those beans would be created by a separate Java Config configuration file. Also note that everything <em>is</em> wired up correctly - I know this because everything works perfectly when the <code>@Autowired</code> tags are on the corresponding private member fields inside of <code>Module3Bean1</code>.</p> <p>FWIW, I tried adding an <code>@DependsOn</code> annotation to <code>module3Bean1()</code> method, but had the same results. I guess I just would really like to understand this behavior, is it correct (I suspect it is, but why)?</p> <p>Finally, I found an acceptable workaround shown here:</p> <pre><code>@Configuration public class Module3ConfigClass { @Bean @Autowired public Module3Bean1 module3Bean1(Module1Bean1 module1Bean1, Module2Bean1 module2Bean1) { return new Module3Bean1(module1Bean1, module2Bean1); } } </code></pre> <p>This seems fine to me, but if anyone would care to comment on it, that would be welcome as well.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload