Spring ClassPathXmlApplicationContext Example

By Arvind Rai, November 07, 2021
The ClassPathXmlApplicationContext fetches ApplicationContext using XML configurations. Find some of the constructors of ClassPathXmlApplicationContext class.
ClassPathXmlApplicationContext(String configLocation)
ClassPathXmlApplicationContext(String... configLocations)
ClassPathXmlApplicationContext(String[] configLocations, ApplicationContext parent)
ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) 
The ClassPathXmlApplicationContext is useful for test harnesses.

Using ClassPathXmlApplicationContext

SpringDemo.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
            ApplicationContext context = 
			   new ClassPathXmlApplicationContext(new String[] {"app-conf.xml", "spring-config.xml"});
            
            Entitlement ent=(Entitlement) context.getBean("entitlement");
            System.out.println(ent.getName());
            
            Subscription sub=(Subscription) context.getBean("subscription");
            System.out.println(sub.getName());
    } 
} 
spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
     
    <bean id="entitlement" class="com.concretepage.Entitlement">
	    <property name="name" value="Entitlement"/>
	    <property name="time" value="20"/>
    </bean>
</beans> 
app-conf.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
     
    <bean id="subscription" class="com.concretepage.Subscription">
	    <property name="name" value="Subscription"/>
	    <property name="type" value="Weekly"/>
    </bean>
</beans> 
Entitlement.java
package com.concretepage;
public class Entitlement {
	private String name;
	private int time;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
} 
Subscription.java
package com.concretepage;
public class Subscription {
	private String name;
	private String type;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}	
} 
Output
Entitlement
Subscription 

Reference

Class ClassPathXmlApplicationContext
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us