介绍:
Spring提供了两种类型的容器:
- BeanFactory :它支持bean实例化和连接
- ApplicationContext :它扩展了BeanFactory ,因此提供了所有这些功能,就像BeanFactory一样。 此外,它提供BeanPostProcessor的自动注册,国际化以及更多功能
Spring容器负责实例化和管理Spring bean的生命周期。 ClassPathXmlApplicationContext是一个实现org.springframework.context.ApplicationContext接口的类。
在本快速教程中,我们将学习如何使用ClassPathXmlApplicationContext 。
最初设定:
假设我们有一个名为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>
使用
当使用ClassPathXmlApplicationContext时 ,容器从CLASSPATH中存在的给定xml文件中加载bean定义。
现在我们已经在应用程序上下文中定义了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定义将覆盖较早加载的文件中定义的定义。
在构造xml定义的应用程序上下文时,我们有时可以使用classpath *:前缀:
ApplicationContext context= new ClassPathXmlApplicationContext("classpath*:appContext.xml");
此前缀指定必须将具有给定名称的所有类路径资源合并在一起以形成最终的应用程序上下文定义。
注册一个
WebApplicationContext已经具有用于正确关闭IoC容器的代码。
但是, 对于任何非Web Spring应用程序,我们必须使用registerShutdownHook()方法在应用程序关闭期间正常关闭Spring IoC容器 。 我们可以为bean定义销毁前的方法,这些方法将被调用以释放所有持有的资源。
让我们在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中进行配置。
现在让我们将关闭钩子注册到我们的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