我有一個帶有 bean 的 xml 檔案,如下所示:
<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>
它有多達 30 個 bean,類 person 和 id 從 1 到 30。
現在我想列印它們,我知道我可以這樣做:
@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);
}
}
但是有沒有更好的方法從這個 xml 檔案中獲取所有“bean”或人員?
uj5u.com熱心網友回復:
有一個getBeansOfType()方法ApplicationContext可以回傳給定型別的所有bean。bean 將作為一個映射重新調整,其中鍵是 bean 的名稱,而值是 bean 實體。
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());
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527381.html
標籤:爪哇春天
