Spring IOC容器
spring IOC 容器有两种,分别是 beanfactory 容器和 ApplicationContext 容器。
beanfactory如下:
/*第一步,利用ClassPathResource()API加载路径CLAsspATH下的可用的Bean的xml配置文件 然后利用框架提供的 Xmlbeanfactory() API生成工厂Bean,Xmlbeanfactory()负责创建和初始化所有对象 然后用getBean方法得到所需要Bean并转化类型为真正的对象 */ Xmlbeanfactory factory = new Xmlbeanfactory(new ClassPathResource("Beans.xml")); HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); obj.getMessage();
<?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-3.0.xsd"> <bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> <property name="message" value="Hello World!"/> </bean> </beans>
ApplicationContext接口的实现:FileSystemXmlApplicationContext:从xml文件中加载已经被定义的bean,需要提供的参数为完整的XML文件路径
ClasspathXmlApplicationCOntext:从xml文件中加载已经被定义的bean,但从CLAsspATH加载xml文件
package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApp { public static void main(String[] args) { //第一步 ApplicationContext context = new FileSystemXmlApplicationContext("C:/Users/Zara/workspace/HelloSpring/src/Beans.xml"); //第二步 HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); } }
Spring Bean 的作用域
singleton:是bean的默认作用域;当作用域为singleton时,IOC容器只会存在一个共享的bean实例,多次getBean时,返回的都是同一个Bean
<bean id="..." class="..." scope="singleton"> <!-- collaborators and configuration for this bean go here --> </bean>
prototype:表示一个bean的定义对应多个对象实例,每次getbean时都会返回一个新的bean实例;
spring的依赖注入
基于构造函数的注入
<!-- id是bean的id,用于识别bean; class是bean所对应的类--> <bean id="textEditor" class="com.tutorialspoint.TextEditor"> <!--constructor-arg表示基于构造函数注入 ,ref表示注入的值是引用而非一般的数值--> <constructor-arg ref="spellChecker"/> </bean>
<bean id="foo" class="x.y.Foo"> <!-- 当构造函数存在多个参数时,按顺序定义即可按顺序传参--> <constructor-arg ref="bar"/> <constructor-arg ref="baz"/> </bean>
基于设值函数的依赖注入
<bean id="textEditor" class="com.tutorialspoint.TextEditor"> <property name="spellChecker" ref="spellChecker"/> <!-- property表示基于设值函数注入,设值函数的名字一定要是 setSpellChecker()--> <property name="name" value="John Doe"/> <!-- name是属性的名字,value是属性的值--> </bean>
基于注解的配置
@required:用在set方法上,一旦用了这个注解,bean在初始化时就必须对这个值进行依赖注入;否则报错
public class Zoo { private Dog dog ; public Dog getDog() { return dog; } @required //如果xml文件中没有对Dog属性进行注入,则会报错 public void setDog(Dog dog) { this.dog = dog; } }
@Autowired:可以不写依赖注入的配置,让容器自己寻找依赖并注入
public class Zoo { @Autowired private Dog dog ; public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } }