【对象的注入】
IOC容器的对象实例化是通过配置文件来实现的。术语上这叫做注入。注入有两种形式,采用构造方法注入和采用setter注入。具体的注入形式如下
**************构造方法方式*******************
UserManagerImpl类:
package com.bjpowernode.spring.manager;
import com.bjpowernode.spring.dao.UserDao;
public class UserManagerImpl implements UserManager {
private UserDao userDao;
public UserManagerImpl(UserDao userDao) {
this.userDao = userDao;
}
}
配置文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="userDao4Mysql" class="com.bjpowernode.spring.dao.UserDao4MySqlImpl" />
<bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">
<constructor-arg ref="userDao4Mysql" />
</bean>
</beans>
****************setter方式*****************
UserManagerImpl类:
package com.bjpowernode.spring.manager;
import com.bjpowernode.spring.dao.UserDao;
public class UserManagerImpl implements UserManager {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
配置文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="userDao4Mysql" class="com.bjpowernode.spring.dao.UserDao4MySqlImpl" />
<bean id="userManager" class="com.bjpowernode.spring.manager.UserManagerImpl">
<!-- <constructor-arg ref="userDao4Mysql" /> -->
<property name="userDao" ref="userDao4Mysql" />
</bean>
</beans>
比较:
1.构造方法:
对于依赖关系无须变化的Bean,构造注入更有用处;因为没有setter方法,所有的依赖关系全部在构造器内设定,因此,不用担心后续代码对依赖关系的破坏。依赖关系只能在构造器中设定,则只有组件的创建者才能改变组件的依赖关系。对组件的调用者而言,组件内部的依赖关系完全透明,更符合高内聚的原则。
构造注入可以在构造器中决定依赖关系的注入顺序。
2,setter方法:
与传统的JavaBean的写法更相似,程序员更容易理解、接受,通过setter方式设定依赖关系显得更加直观、明显;对于复杂的依赖关系,如果采用构造注入,会导致构造器过于臃肿,难以阅读。Spring在创建Bean实例时,需要同时实例化其依赖的全部实例,因而导致死你功能下降。而使用设置注入,则避免这下问题;尤其在某些属性可选的情况下,多参数的构造器更加笨拙。
【属性编辑器】
Spring内置了一些属性编辑器,可以将一些普通常用的属性注入,将Spring配置文件中的String类型转换成相应的Java对象。例如一个类里面的一个整型属性,在配置文件中我们是通过String类型的数字直接进行配置即可。如下示例:
Bean1类:
package com.bjpowernode.spring;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Bean1 {
private String strValue;
private int intValue;
private List listValue;
private Set setValue;
private String[] arrayValue;
private Map mapValue;
private Date dateValue;
//get和set略
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-lazy-init="true">
<bean id="bean1" class="com.bjpowernode.spring.Bean1">
<property name="strValue" value="Hello_Spring" />
<!-- <property name="intValue" value="123"/> -->
<property name="intValue">
<value>123</value>
</property>
<property name="listValue">
<list>
<value>list1</value>
<value>list2</value>
</list>
</property>
<property name="setValue">
<set>
<value>set1</value>
<value>set2</value>
</set>
</property>
<property name="arrayValue">
<list>
<value>array1</value>
<value>array2</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="k1" value="v1" />
<entry key="k2" value="v2" />
</map>
</property>
</bean>
</beans>
测试方法:
package test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bjpowernode.spring.Bean1;
import junit.framework.TestCase;
public class InjectionTest extends TestCase {
private BeanFactory factory;
@Override
protected void setUp() throws Exception {
String[] configLocations = new String[] {
"applicationContext-beans.xml"};
factory = new ClassPathXmlApplicationContext(configLocations);
}
@Override
protected void tearDown() throws Exception {
}
public void testInjection1() {
Bean1 bean1 = (Bean1) factory.getBean("bean1");
System.out.println("bean1.strValue=" + bean1.getStrValue());
System.out.println("bean1.intValue=" + bean1.getIntValue());
System.out.println("bean1.listValue=" + bean1.getListValue());
System.out.println("bean1.setValue=" + bean1.getSetValue());
System.out.println("bean1.arrayValue=" + bean1.getArrayValue());
System.out.println("bean1.mapValue=" + bean1.getMapValue());
System.out.println("bean1.dateValue=" + bean1.getDateValue());
}
}
【自定义属性编辑器】
Spring具有多个自定义编辑器,它们能够自动把注入的String值转化为更复杂的类型。例如Date类型,如果直接按照上面实例的方式进行配置,就会报错如下:
org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'bean' defined in class path resource[applicationContext.xml]: Initialization of bean failed; nested exception isorg.springframework.beans.TypeMismatchException: Failed to convert propertyvalue of type [java.lang.String] to required type [java.util.Date] for property'date';
因为Spring没有内置Date的属性编辑器,需要我们自己创建。创建过程:
1.编写UtilDatePropertyEditor类,继承PropertyEditorSupport,覆盖setAsText()方法,其中text参数就是配置文件中的值。我们的任务就是把text转换成date类型的值。
package com.bjpowernode.spring;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* java.util.Date属性编辑器
* @author Administrator
*
*/
public class UtilDatePropertyEditor extends PropertyEditorSupport {
private String pattern;
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("---UtilDatePropertyEditor.setAsText()--->" + text);
try {
Date date = new SimpleDateFormat(pattern).parse(text);
this.setValue(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new IllegalArgumentException(text);
}
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
2.将自定义的属性编辑器注入到spring中,为了方便管理我们再新建一个配置文件applicationContext-editor.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="customEditors" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.bjpowernode.spring.UtilDatePropertyEditor">
<property name="pattern" value="yyyy年MM月dd日"/>
</bean>
</entry>
</map>
</property>
</bean>
</beans>