Issue
I have an xml file with beans which look like this:
<bean class="org.example.domain.Person" id="1">
<property name="first_name" value="Jillian"/>
<property name="last_name" value="Palethorpe"/>
<property name="email" value="[email protected]"/>
<property name="company_name" value="Layo"/>
</bean>
It has up to 30 beans with class person and id from 1 to 30.
Now i want to print them I know that I could do this like that:
@SpringBootApplication
@ImportResource("classpath:beans.xml")
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Main.class, args);
Person first = applicationContext.getBean("1", Person.class);
Person second = applicationContext.getBean("2", Person.class);
System.out.println(first);
System.out.println(second);
}
}
But is there a better way to get all of the "beans" or persons from this xml file?
Solution
There is a getBeansOfType()
method in the ApplicationContext
which can return all beans of a given type. The beans will be retuned as a map which the key is the name of the bean while the value is the bean instance.
Map<String, Person> beans = applicationContext.getBeansOfType(Person.class);
Person person1 = beans.get("1");
Person person2 = beans.get("2");
List<Person> allPersons = new ArrayList<>(beans.values());
Answered By - Ken Chan
Answer Checked By - Willingham (JavaFixing Volunteer)