一、获取ApplicationContext的方法
1.通过ClassPathXmlApplicationContext获取;
2.通过FileSystemXmlApplicationContext获取;
3.通过AnnotationConfigApplicationContext获取;
4.通过继承ApplicationContextAware获取;
二、代码示例
如下示例提供4种方式获取ApplicationContext,然后再通过上下文获取Bean对象。
App.java文件:
public class App {
public static void main( String[] args )
{
//方式1:spring-config.xml文件必须在jar包resource目录下
ApplicationContext context1 = new ClassPathXmlApplicationContext("spring-config.xml");
Bean1 b1 = context1.getBean(Bean1.class);
System.out.println(b1.hello("b1"));
//方式2:spring-config.xml文件必须在程序运行当前目录下
ApplicationContext context2 = new FileSystemXmlApplicationContext("spring-config.xml");
Bean1 b2 = context2.getBean(Bean1.class);
System.out.println(b2.hello("b2"));
//方式3:MyConfig设置ComponentScan的路径,并且Bean1使用@Component注解
ApplicationContext context3 = new AnnotationConfigApplicationContext(MyConfig.class);
Bean1 b3 = context3.getBean(Bean1.class);
System.out.println(b3.hello("b3"));
//方式4:MyContext实现ApplicationContextAware接口
ApplicationContext context4 = MyContext.getApplicationContext();
Bean1 b4 = context4.getBean(Bean1.class);
System.out.println(b4.hello("b4"));
}
}
Bean1.java文件:
@Component
public class Bean1 {
Bean1(){
System.out.println("=================Bean1构造");
}
public String hello(String name){
return "=================hello " + name;
}
}
spring-config.xml配置文件:(方式1和方式2使用)
<?xml version="1.0" encoding="UTF-8"?>
<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="Bean1" class="com.gk.testcontext.Bean1"></bean>
</beans>
MyConfig.java文件:(方式3使用)
@Configuration
@ComponentScan({"com.gk"})
public class MyConfig {
MyConfig(){
System.out.println("=================MyConfig构造");
}
}
MyContext.java文件:(方式4使用)
@Component
public class MyContext implements ApplicationContextAware {
private static ApplicationContext myApplicationContext;
MyContext(){
System.out.println("=================MyContext构造");
}
@Override
public void setApplicationContext(ApplicationContext context){
myApplicationContext = context;
}
public static ApplicationContext getApplicationContext(){
return myApplicationContext;
}
}
pom文件中增加如下依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
</dependencies>
执行结果: