超级通道: Spring代码实例系列-绪论
一般我们习惯通过setter进行注入,例如Spring代码实例系列-02:松耦合loose coupling等都是setter注入,本章给与一个简单的构造器注入实例。主要应用到的技术有:
1. 注入bean
2. setter注入
3. constructor注入
4. 松耦合
0.目录
project
\---src
\---main
\---java
| \---pers
| \---hanchao
| \---constructor
| \---App.java
| \---MyFavoriteFruit.java
| \---Fruit.java
| \---Apple.java
| \---Orange.java
\---resources
\---spring-config
\---spring-constructor.xml
1.App.java
package pers.hanchao.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* <p>spring构造注入示例:通过配置xml中的constructor-arg标签</p>
* @author hanchao 2018/1/7 12:32
**/
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config/spring-constructor.xml");
MyFavoriteFruit myFavoriteFruit = (MyFavoriteFruit) context.getBean("myFavoriteFruit");
myFavoriteFruit.showMyFavoriteFruit();
}
}
2.spring-constructor.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通过settr注入-->
<!--<bean id="myFavoriteFruit" class="pers.hanchao.loosecoupling.MyFavoriteFruit">-->
<!--<property name="fruit" ref="apple"/>-->
<!--</bean>-->
<bean id="myFavoriteFruit" class="pers.hanchao.constructor.MyFavoriteFruit">
<constructor-arg ref="orange"/>
</bean>
<bean id="apple" class="pers.hanchao.constructor.Apple"/>
<bean id="orange" class="pers.hanchao.constructor.Orange"/>
</beans>
3.MyFavoriteFruit.java
package pers.hanchao.constructor;
public class MyFavoriteFruit {
private Fruit fruit;
// //通过setter注入
// public void setFruit(Fruit fruit) {
// this.fruit = fruit;
// }
//通过constructor注入
public MyFavoriteFruit(Fruit fruit) {
this.fruit = fruit;
}
public void showMyFavoriteFruit(){
System.out.println("My favorite fruit is " + this.fruit.showName());
}
}
4.Fruit.java
package pers.hanchao.constructor;
public interface Fruit {
public String showName();
}
4.Apple.java
package pers.hanchao.constructor;
public class Apple implements Fruit {
@Override
public String showName() {
return "apple";
}
}
6.Orange.java
package pers.hanchao.constructor;
public class Orange implements Fruit {
@Override
public String showName() {
return "orange";
}
}
7.result
My favorite fruit is orange