Spring依赖注入,属性注入和构造函数注入,spring构造函数,Spring是一个jav
Spring依赖注入,属性注入和构造函数注入,spring构造函数,Spring是一个jav
Spring是一个java框架,依赖注入是指类实例不是通过调用类的构造函数来实现,而是通过xml或者注解注入来自动生成类的实例,这样做可以将类和类之间直接通过构造函数来相互依赖改进为通过配置文件或者注解来依赖,从而使类和类不必通过构造函数直接耦合,增加程序的灵活性。
下面我们通过实战看下如何使用spring的依赖注入,建议使用spring提供的开发工具sts。
首先新建一个maven项目,在引入spring相关的maven依赖项,在pom.xml中添加如下依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.0.RC2</version> </dependency>
然后,需要在项目中添加source folder,src/main/resources,然后在此文件夹下新建一个xml文件,命名为spring.xml
在spring文件中添加下面内容:
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"></beans>
这样我们的准备工作就做完了,我们添加了spring的依赖jar包,并且在资源文件路径下添加了spring.xml来做依赖注入的配置文件。下面看下我们这个demo要做什么。
假定我们要定制一辆车Car,我们需要一个People来驾驶这辆车。
首先我们定义Car类,假定Car类有两个属性品牌brand和颜色color。
package cn.outofmemory.hellospring;public class Car { public Car() { } public Car(String brand, String color) { this.color = color; this.brand = brand; } private String brand; private String color; /** * @return the brand */ public String getBrand() { return brand; } /** * @param brand the brand to set */ public void setBrand(String brand) { this.brand = brand; } /** * @return the color */ public String getColor() { return color; } /** * @param color the color to set */ public void setColor(String color) { this.color = color; }}
我们再看下People类,假定他有一个属性是自己拥有的car,和一个方法drive()驾驶拥有的car。
package cn.outofmemory.hellospring;public class People { private Car myCar; /** * @return the myCar */ public Car getMyCar() { return myCar; } /** * @param myCar the myCar to set */ public void setMyCar(Car myCar) { this.myCar = myCar; } public void drive() { String drivingMessage = String.format("I am driving, my car's %s, its color is %s", this.getMyCar().getBrand(), this.getMyCar().getColor()); System.out.println(drivingMessage); }}
为了可以通过配置让不同的People可以驾驶不同的Car,我们需要定义spring.xml配置文件:
首先我们定义两辆车,一辆是红色的宝马,另一个是白色的奔驰。
在spring.xml的根节点beans中添加如下定义:
<bean id="carA" class="cn.outofmemory.hellospring.Car"> <property name="brand" value="宝马"/> <property name="color" value="红色"/></bean><bean id="carB" class="cn.outofmemory.hellospring.Car"> <constructor-arg name="brand" value="奔驰"/> <constructor-arg name="color" value="白色"/></bean>
可以看到carA是通过属性输入,而carB是通过构造函数注入的,下面我们在定义一个People 的bean。
<bean class="cn.outofmemory.hellospring.People"> <property name="myCar" ref="carA"/></bean>
People是通过属性注入的,还有一点是People的这个bean未指定id属性,只是指定了class属性,也就是说我们不能通过名称来获得people类的实例,而只能通过class来获得。
上述配置文件中定义了需要的类,下面我们来使用这些类和bean,我们需要在App.java中使用定义的spring配置文件,并让people drive()
package cn.outofmemory.hellospring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml"); People commonPeople = appContext.getBean(People.class); commonPeople.drive(); }}
在App.java的main方法中首先声明了appContext,这个appContext读取了上面的配置文件spring.xml,然后我们声明commonPeople实例,并调用其drive方法。
运行App,会得到如下输出:
2013-6-14 17:11:12 org.springframework.context.support.AbstractApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7: startup date [Fri Jun 14 17:11:12 CST 2013]; root of context hierarchy2013-6-14 17:11:12 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [spring.xml]2013-6-14 17:11:12 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@b61fd1: defining beans [carA,carB,cn.outofmemory.hellospring.People#0]; root of factory hierarchyI am driving, my car's 宝马, its color is 红色
最下面的一行是我们的输出信息,而上面的信息是spring框架打印出来的信息。
上述是个spring的简单的注入入门实例,我们再看一个稍稍复杂一点的,上面的people是一个普通人,我们再来定义一个高富帅,高富帅与普通人的区别在于它有很多车,而在每次驾驶之前都要随机选一辆车来驾驶。
我们需要一个新的People类,TallRichHansom,根据上述特点,他的类定义如下:
package cn.outofmemory.hellospring;import java.util.List;import java.util.Random;public class TallRichHansom extends People { private List<Car> cars; /** * @return the cars */ public List<Car> getCars() { return cars; } /** * @param cars the cars to set */ public void setCars(List<Car> cars) { this.cars = cars; } @Override public void drive() { int carCount = this.getCars().size(); int choiseIndex = new Random().nextInt(carCount); Car choise = this.getCars().get(choiseIndex); this.setMyCar(choise); super.drive(); } }
我们给高富帅添加了cars属性,并重写了其drive方法,在每次drive之前都做一下随机选车。
下面我们给高富帅配置spring文件,在spring.xml中添加下面bean定义,我们给高富帅设置了cars属性,这个属性是一个list,需要在property节点中首先添加list节点,然后添加一个一个的car节点:
<bean class="cn.outofmemory.hellospring.TallRichHansom"> <property name="cars"> <list> <ref bean="carA"/> <ref bean="carB"/> <bean class="cn.outofmemory.hellospring.Car"> <property name="brand" value="法拉利"/> <property name="color" value="黑色" /> </bean> </list> </property> </bean>
然后我们在App.java中让高富帅驾驶自己的车三次。
package cn.outofmemory.hellospring;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml"); People trh = appContext.getBean(TallRichHansom.class); trh.drive(); trh.drive(); trh.drive(); }}
输出高富帅驾车的结果是随机显示的,如果高富帅那天心血来潮想买新车的话,我们没有必要修改java代码,只需要在spring.xml中给他添加新车的配置就可以了。
下载示例项目
用户点评