How to Use Spring ApplicationContext

There are two common ways to use ApplicationContext in Spring.

  1. Create ApplicationContext by using an XML configuration file.

First, you need to define the implementation class of ApplicationContext in the Spring configuration file. For example, you can use the ClassPathXmlApplicationContext implementation class.

<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">

    <!-- 定义ApplicationContext -->
    <bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            <list>
                <value>spring-config.xml</value>
                <!-- 可以添加更多的配置文件路径 -->
            </list>
        </constructor-arg>
    </bean>

    <!-- 其他bean的定义 -->
</beans>

Next, load the ApplicationContext in the Java code.

// 加载Spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");

// 获取bean
SomeBean someBean = applicationContext.getBean(SomeBean.class);
  1. Create an ApplicationContext based on annotations.

Firstly, you need to add the @Configuration annotation to the Java configuration class, and also use the @ComponentScan annotation to specify the package paths that need to be scanned.

@Configuration
@ComponentScan("com.example")
public class AppConfig {

}

Next, load the ApplicationContext in the Java code.

// 加载配置类
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

// 获取bean
SomeBean someBean = applicationContext.getBean(SomeBean.class);

These are two common ways to use ApplicationContext, choose the one that best fits your specific needs.

bannerAds