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 {
}
Also, I have a class with an Autowired variable like this:
public class Collector {
@Autowired
private Collection<A> objects;
public Collection<A> getObjects() {
return objects;
}
}
My context file consists of these 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 some codes as follows:
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 reasons I’m not willing to use xml context file. Besides it, I prefer to create the objects with the new operator rather than using the getBean() method. Nevertheless, since the AutoWiring is really good idea in programming, I don’t want to lose it.
Now I have two questions!!
-
how can I
AutoWireclasses that implements theAInterface without using the xml context file?
Is it possible at all? -
when I change the
scopeof a bean fromsingltonto
prototypeas follows:<bean id="b" class="org.iust.ce.me.B" scope="prototype"></bean>and instantiate several beans of it, only the bean which was instantiated during creating
context, isinjectedintoAutoWiredvariable. Why?
Any help will be appreciated.
Not sure the version of Spring you are using. But currently you can use
@Configurationto replace .xml. Take a look at @ConfigurationBelow is the code in documentation