一、依赖注入的方式
三种:接口注入,设置属性注入,构造方法注入。
在Spring中使用多的是设置属性注入,通过setter方法传入被调用者的实例,注入方法简单直观。
下面是一个例子。
首先是person.class
package wen; public class Person { public String name ; public String password ; public boolean hslogin ; public String getName() { return name; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } public void setHslogin(boolean hslogin) { this.hslogin = hslogin; } }
配置文件
<?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-2.0.xsd"> <bean id="person" class="wen.Person"> <property name="name" value="lsj" /> <property name="password" value="1234"/> <property name="hslogin" value="true"/> </bean> </beans>
测试文件
package wen; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Factory1 { public static void main(String [] args){ Resource res = new ClassPathResource("applicationContext.xml"); DefaultListableBeanFactory factory= new DefaultListableBeanFactory (); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(res); Person person = (Person)factory.getBean("person") ; System.out.println(person.name); System.out.println(person.password); System.out.println(person.hslogin); } }
二、bean 的配置
- bean的scope
如果类要及时更新
<bean id="date" class="java.util.Date" scope="prototype"/>
默认情况 为singleton
当请求相同的bean时,不再重新生成新的对象。
- 注入类型
注入基本类型
同上
注入引用类型
用<ref>代替<value>
list和数组类型注入
set/map等注入
三、bean的深入配置
- 构造函数注入
这种方法的优点是强制注入,保证bean在创建时就正确的初始化了。
- 实例工厂注入
略