Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to AutoWire an object without Spring XML context file?
    primarykey
    data
    text
    <p>I have an Interface with <code>Component</code> annotation and some classes that implemented it as follows: </p> <pre><code>@Component public interface A { } public class B implements A { } public class C implements A { } </code></pre> <p>Also, I have a class with an <code>Autowired</code> variable like this:</p> <pre><code>public class Collector { @Autowired private Collection&lt;A&gt; objects; public Collection&lt;A&gt; getObjects() { return objects; } } </code></pre> <p>My context file consists of these definitions:</p> <pre><code>&lt;context:component-scan base-package="org.iust.ce.me"&gt;&lt;/context:component-scan&gt; &lt;bean id="objectCollector" class="org.iust.ce.me.Collector" autowire="byType"/&gt; &lt;bean id="b" class="org.iust.ce.me.B"&gt;&lt;/bean&gt; &lt;bean id="c" class="org.iust.ce.me.C"&gt;&lt;/bean&gt; </code></pre> <p>And in the main class, I have some codes as follows:</p> <pre><code>ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); B b = (B) context.getBean("b"); C c = (C) context.getBean("c"); Collector objectCollector = (Collector) context.getBean("objectCollector"); for (A object : objectCollector.getObjects()) { System.out.println(object); } </code></pre> <p>Output:</p> <pre><code>org.iust.ce.me.B@1142196 org.iust.ce.me.C@a9255c </code></pre> <hr> <p>These codes work well, but for some reasons I’m not willing to use xml context file. Besides it, I prefer to create the objects with the <code>new</code> operator rather than using the <code>getBean()</code> method. Nevertheless, since the <code>AutoWiring</code> is really good idea in programming, I don’t want to lose it. </p> <p>Now I have two questions!! </p> <ol> <li><p>how can I <code>AutoWire</code> classes that implements the <code>A</code> Interface without using the xml context file?<br> Is it possible at all?</p></li> <li><p>when I change the <code>scope</code> of a bean from <code>singlton</code> to <code>prototype</code> as follows: </p> <p><code>&lt;bean id="b" class="org.iust.ce.me.B" scope="prototype"&gt;&lt;/bean&gt;</code></p> <p>and instantiate several beans of it, only the bean which was instantiated during creating <code>context</code>, is <code>injected</code> into <code>AutoWired</code> variable. Why?</p></li> </ol> <p>Any help will be appreciated. </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.
    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