配置bean
配置形式:基于XML文件的方式;基于注解的方式
Bean的配置方式:通过全类名(反射)、通过工厂方法(静态工厂方法&实例工厂方法)、FactoryBean
依赖注入的方式:属性注入;构造器注入
Bean之间的关系:继承;依赖
Bean的作用域:singleton;prototype;web环境作用域
如何在Spring的IOC容器里配置Bean:
在xml文件中通过bean节点来配置bean。
id:Bean的名称
在IOC容器中必须是唯一的;
若id没有指定,Spring自动将权限定性类名作为Bean的名字;
id可以指定多个名字,名字之间可用逗号、分号、或空格分隔。
在SpringIOC容器读取Bean配置创建Bean实例之前,必须对它进行实例化,只有在容器实例化后,才可以从IOC容器里获取Bean实例并使用。
Spring提供了两种类型的IOC容器实现:
1、BeanFactory,IOC容器的基本实现:
它是Spring框架的基础设施,面向Spring本身;
2、ApplicationContext提供了更多的高级特性,是BeanFactory的子接口;
ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都直接使用ApplicationContext而非底层的BeanFactory;
无论使用何种方式,配置文件是相同的;
ApplicationContext:
ApplicationContext的主要实现类:
1、ClassPathXmlApplicationContext:从类路径下加载配置文件
2、FileSystemXmlApplicationContext:从文件系统中加载配置文件;
ConfigurableApplicationContext扩展于ApplicationContext,新增加两个主要方法:
refresh()和close(),让ApplicationContext具有启动、刷新和关闭上下午的能力;
ApplicationContext在初始化上下文时就实例化所有单例的Bean。
WebApplicationContext是专门为WEB应用而准备的,它允许从相对WEB根目录的路径中完成初始化工作
下面看个实例:
创建HelloWorld.java
package spring.beans;
public class HelloWorld {
private String name;
public void setName(String name){
this.name=name;
}
public void hello(){
System.out.println("hello:"+name);
}
}
创建配置文件applicationContext.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.xsd">
<!--
配置Bean
class:bean的全类名,通过反射的方式在IOC容器中创建bean,所以要求bean中必须有无参数的构造器
id:标识容器中的bean,通过getBean("id")来引用这个bean
-->
<bean id="helloWorld" class="spring.beans.HelloWorld">
<!-- 通过属性注入 -->
<property name="name" value="Spring"></property>
</bean>
</beans>
创建Main.java
package spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
//1.创建Spring的IOC容器对象
//ApplicationContext代表IOC容器
//ClassPathXmlApplicationContext 是 ApplicationContext接口的实现类,该实现来从类路径下来加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取Bean实例
//利用id定位到IOC容器中的bean
HelloWorld helloWorld =(HelloWorld) ctx.getBean("helloWorld");
//利用类型返回IOC容器中的Bean,但要求IOC容器中必须只有一个该类型的Bean
//HelloWorld helloWorld =ctx.getBean(HelloWorld.class);
System.out.println(helloWorld);
//3.调用hello方法
helloWorld.hello();
}
}
执行Main.java