先来一个骑士
package root;
/**
* @author erniu.wzh
* @date 2021/1/13 8:37 下午
*/
public interface Knight {
public void embarkOnQuest();
}
package root;
/**
* @author erniu.wzh
* @date 2021/1/13 8:21 下午
*/
public class BraveKnight implements Knight{
private final Quest quest;
public BraveKnight(Quest quest) {
this.quest = quest;
}
public void embarkOnQuest() {
quest.embark();
}
}
再来一个请求
package root;
/**
* @author erniu.wzh
* @date 2021/1/13 8:22 下午
*/
public interface Quest {
public void embark();
}
package root;
import java.io.PrintStream;
/**
* @author erniu.wzh
* @date 2021/1/13 8:23 下午
*/
public class SlayDragonQuest implements Quest{
private final PrintStream stream;
public SlayDragonQuest(PrintStream stream) {
this.stream = stream;
}
public void embark() {
stream.println("Embarking on quest to slay the dragon!");
}
}
如果想让勇敢的骑士去打龙,需要这样
package root;
/**
* @author erniu.wzh
* @date 2021/1/13 8:54 下午
*/
public class Main3 {
public static void main(String[] args) {
Quest quest = new SlayDragonQuest(System.out);
Knight knight = new BraveKnight(quest);
knight.embarkOnQuest();
}
}
先构造一个quest,再构造一个knight,再打龙
如果用Spring的依赖注入,就不需要这样构造了
使用Spring的依赖注入有两种方法
方法1:使用xml文件配置bean
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="knight" class="root.BraveKnight">
<constructor-arg ref="quest"/>
</bean>
<bean id="quest" class="root.SlayDragonQuest">
<constructor-arg value="#{T(System).out}"/>
</bean>
</beans>
package root;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author erniu.wzh
* @date 2021/1/13 8:25 下午
*/
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("knights.xml");
Knight knight = classPathXmlApplicationContext.getBean(Knight.class);
knight.embarkOnQuest();
classPathXmlApplicationContext.close();
}
}
方法2:使用config配置bean
package root;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author erniu.wzh
* @date 2021/1/13 8:42 下午
*/
@Configuration
public class KnightConfig {
@Bean
public Knight knight() {
return new BraveKnight(quest());
}
@Bean
public Quest quest() {
return new SlayDragonQuest(System.out);
}
}
package root;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author erniu.wzh
* @date 2021/1/13 8:46 下午
*/
public class Main2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("root");
Knight knight = context.getBean(Knight.class);
knight.embarkOnQuest();
context.close();
}
}