I have an interface with Component annotation and some classes that implemented it as follows:
@Component public interface A { } public class B implements A { } public class C implements A { }
In addition, I have a class with the Autowired variable as follows:
public class Collector { @Autowired private Collection<A> objects; public Collection<A> getObjects() { return objects; } }
My context file consists of the following definitions:
<context:component-scan base-package="org.iust.ce.me"></context:component-scan> <bean id="objectCollector" class="org.iust.ce.me.Collector" autowire="byType"/> <bean id="b" class="org.iust.ce.me.B"></bean> <bean id="c" class="org.iust.ce.me.C"></bean>
And in the main class, I have several codes:
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); }
Output:
org.iust.ce.me.B@1142196 org.iust.ce.me.C@a9255c
These codes work well, but for some reason I don't want to use the xml context file. In addition, I prefer to create objects using the new operator instead of using the getBean() method. However, since AutoWiring really good idea in programming, I don't want to lose it.
Now I have two questions !!
How can I AutoWire classes that implement the A interface without using the xml context file?
Is this even possible?
when I change the scope bean from singlton to prototype as follows:
<bean id="b" class="org.iust.ce.me.B" scope="prototype"></bean>
and create some beans, only the bean that was created when the context was created is injected in the Autowired variable. Why?
Any help would be appreciated.
source share