首先说一下什么是依赖注入,刚开始接触spring的时候不理解;现在根据初步理解,依赖注入,就是将xml文件中设置的属性值,注入到类的实例化对象中!
下面介绍spring的依赖注入
一、set注入
二、构造函数注入
下面的代码展示了这两种注入方式,注意 将set注入,注释掉可以正常执行;将构造函数注释掉便不能正常执行;因为注释掉构造函数,根据Java反射机制生成的反射对象就没有构造函数,而类本身是有构造函数的,所以在实例化对象的时候就会报错。当然如果类中没有写构造函数,则不用也不能够使用构造函数注入。
set注入与构造函数注入同时存在时,set注入会覆盖掉构造函数注入(与XML中的顺序无关)
public interface Action { public String execute(String str); }
public class UpperAction implements Action { private String message; private int num; public UpperAction(String str,int i) { this.message = str; this.num = i; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getMessage() { return message; } public void setMessage(String string) { message = string; } public String execute(String str) { return (getMessage() + str + Integer.toString(num)).toUpperCase(); } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; public class TestAction { public static void main(String[] args) throws FileNotFoundException { Resource is = new FileSystemResource("E:\Users\panteng\Workspaces\MyEclipse 10\mySpring\src\applicationContext.xml"); BeanFactory factory = new XmlBeanFactory((Resource) is); Action bean = (Action) factory.getBean("theAction"); //((UpperAction) bean).setNum(6); System.out.println(bean.execute("Rod")); } }
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="theAction" class="UpperAction"> <!-- abstract="false" lazy-init="default" autowire="default">--> <!--构造函数注入 --> <constructor-arg value="admin" type="String" index = "0"></constructor-arg> <constructor-arg value="5" type="int" index = "1"></constructor-arg> <!-- Set 注入 --> <property name="message" value = "style1"></property> <property name="num"> <value type = "int">3</value> </property> </bean> </beans>