Spring容器对象
BeanFactory
BeanFactory接口:spring容器中具有代表性的容器就是BeanFactory接口,这个是spring容器的顶层接口,提供了容器最基本的功能。
里面常用的一些方法:
//按bean的id或者别名查找容器中的bean
Object getBean(String name) throws BeansException
//这个是一个泛型方法,按照bean的id或者别名查找指定类型的bean,返回指定类型的bean对象
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
//返回容器中指定类型的bean对象
<T> T getBean(Class<T> requiredType) throws BeansException;
ApplicationContext
这个接口继承了BeanFactory接口,所以内部包含了BeanFactory所有的功能,并且在其上进行了扩展,增加了很多企业级功能,比如AOP、国际化、事件支持等等。。
ClassPathXmlApplicationContext
这个类实现了ApplicationContext接口,注意一下这个类名称包含了ClassPath Xml,说明这个容器类可以从classpath中加载bean xml配置文件,然后创建xml中配置的bean对象。
AnnotationConfigApplicationContext
这个类也实现了ApplicationContext接口,注意其类名包含了Annotation和config两个单词,bean的定义支持xml的方式和注解的方式,当我们使用注解的方式定义bean的时候,就需要用到这个容器来装载了,这个容器内部会解析注解来构建构建和管理需要的bean。
案例
创建一个类
public class HelloSpring {
public void hello(){
System.out.println("hello");
}
}
测试类:
public class ClientTest {
@Test
public void testBean(){
//1.bean配置文件位置
String path = "classpath:/bean/beans.xml";
//2.创建ClassPathXmlApplicationContext容器,给容器指定需要加载的bean配置文件
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(path);
//3.从容器中获取需要的bean
HelloSpring helloSpring = (HelloSpring)context.getBean("helloSpring");
//4.使用对象
helloSpring.hello();
}
}
xml信息:
<?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-4.3.xsd">
<!--
定义一个bean
id:bean的唯一标识,可以通过这个标识从容器中获取这个bean对象
clss:这个bean的类型,完整类名称
-->
<bean id="helloSpring" class="com.spring.beanDemo.HelloSpring"/>
</beans>
运行输出:
hello
下一篇我们将详解bean的定义。
参考链接:spirng初识