一、设值注入
Plane.java:
public class Plane implements Fly {
public Plane() {
System.out.println("飞机被创建");
}
@Override
public void fly() {
System.out.println("飞机飞");
}
}
HotBallon.java:
public class HotBallon implements Fly {
@Override
public void fly() {
System.out.println("热气球在飞");
}
}
Fly.java:
public interface Fly {
void fly();
}
SuperMan.java:
/超人可以通过工具飞,也可以自己飞
public class SuperMan implements Fly {
private Fly tool;//持有抽象属性
private String name;
public SuperMan() {
}
public SuperMan(Fly tool,String name){
this.tool=tool;
this.name=name;
}
//构造时,指定工具
public SuperMan(Fly tool){
this.tool=tool;
}
public void setTool(Fly tool) {
this.tool = tool;
}
public void setName(String name) {
this.name = name;
}
@Override
public void fly() {
if (tool==null){
System.out.println("超人"+name+"自己飞");
}else {
System.out.println("超人"+name+"通过");
tool.fly();//工具飞行
}
}
}
spring-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 组件扫描,扫描含有注解的类 -->
<context:component-scan base-package="com.wance.spring"/>
<!-- 配置service
<bean> 配置需要创建的对象
id :用于之后从spring容器获得实例时使用
class :需要创建实例的全限定类名
property:类中的成员
property name 成员的名称
property value 成员的值
-->
<!--装配一个Plane对象 -->
<bean id="f1" class="com.wance.entity.Plane">
</bean>
<!--装配第二个Plane对象 -->
<bean id="f2" class="com.wance.entity.Plane">
</bean>
<!--装配一个HotBallon对象 -->
<bean class="com.wance.entity.HotBallon">
</bean>
<!--装配一个SuperMan对象 -->
<bean class="com.wance.entity.SuperMan" id="sm">
<!--通过set值注入,tool属性通过setTool方法,传入上面f1对象-->
<property name="tool" ref="f1" />
//如果上面没有f1引用,可以就地解决,采用下面的方式
<!--
<property name="tool">
<bean class="com.wance.entity.Plane"></bean>
</property>
-->
<!--通过构造注入,通过SuperMan(Tool tool,String name)构造函数注入-->
<constructor-arg ref="f1"/>
<constructor-arg value="king"/>
</bean>
</beans>