javascript
Spring ClassPathXmlApplicationContext
介紹:
Spring提供了兩種類型的容器:
- BeanFactory :它支持bean實(shí)例化和連接
- ApplicationContext :它擴(kuò)展了BeanFactory ,因此提供了所有這些功能,就像BeanFactory一樣。 此外,它提供BeanPostProcessor的自動注冊,國際化以及更多功能
Spring容器負(fù)責(zé)實(shí)例化和管理Spring bean的生命周期。 ClassPathXmlApplicationContext是一個實(shí)現(xiàn)org.springframework.context.ApplicationContext接口的類。
在本快速教程中,我們將學(xué)習(xí)如何使用ClassPathXmlApplicationContext 。
最初設(shè)定:
假設(shè)我們有一個名為Person的Java類:
public class Person {private int id;private String name;...}另外,讓我們在applicationContext.xml中定義bean :
<bean id="person" class="com.programmergirl.domain.Person"><property name="id" value="1"/><property name="name" value="Sam"/> </bean>使用
當(dāng)使用ClassPathXmlApplicationContext時 ,容器從CLASSPATH中存在的給定xml文件中加載bean定義。
現(xiàn)在我們已經(jīng)在應(yīng)用程序上下文中定義了Person bean,讓我們使用它在main()方法中加載bean:
public class MyApp {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");Person person = (Person) context.getBean("person");System.out.println(person.getId() + ":" + person.getName());} }請注意, 我們還可以使用幾個XML配置文件來初始化Spring容器:
ApplicationContext context= new ClassPathXmlApplicationContext("appContext1.xml", "appContext2.xml");在這種情況下,較新的bean定義將覆蓋較早加載的文件中定義的定義。
在構(gòu)造xml定義的應(yīng)用程序上下文時,我們有時可以使用classpath *:前綴:
ApplicationContext context= new ClassPathXmlApplicationContext("classpath*:appContext.xml");此前綴指定必須將具有給定名稱的所有類路徑資源合并在一起以形成最終的應(yīng)用程序上下文定義。
注冊一個
WebApplicationContext已經(jīng)具有用于正確關(guān)閉IoC容器的代碼。
但是, 對于任何非Web Spring應(yīng)用程序,我們必須使用registerShutdownHook()方法在應(yīng)用程序關(guān)閉期間正常關(guān)閉Spring IoC容器 。 我們可以為bean定義銷毀前的方法,這些方法將被調(diào)用以釋放所有持有的資源。
讓我們在Person類中添加一個方法:
public class Person {...public void preDestroy() {System.out.println("Releasing all resources");}}并更新我們的applicationContext.xml :
<bean id="person" class="com.programmergirl.domain.Person" destroy-method="preDestroy"><property name="id" value="1"/><property name="name" value="Sam"/> </bean>使用注釋時,我們可以在方法上使用@PreDestroy注釋,而不是在xml中進(jìn)行配置。
現(xiàn)在讓我們將關(guān)閉鉤子注冊到我們的ApplicationContext :
The above code on execution will print:
Conclusion:
In this article, we learned the basic usage of ClassPathXmlApplicationContext .
翻譯自: https://www.javacodegeeks.com/2019/05/spring-classpathxmlapplicationcontext.html
總結(jié)
以上是生活随笔為你收集整理的Spring ClassPathXmlApplicationContext的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jbpm 和 drools_Drools
- 下一篇: Docker化Spring Boot应用