源码地址 https://manning-content.s3.amazonaws.com/download/9/ef4e0ef-b7bd-4ab8-857d-eb635d18d425/SpringiA4_SourceCode.zip
java依赖注入(Dependency Injection)
方法一,使用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">
<bean id="knight" class="sia.knights.BraveKnight">
<constructor-arg ref="quest" />
</bean>
<!--System.out是一个PrintStream-->
<bean id="quest" class="sia.knights.SlayDragonQuest">
<constructor-arg value="#{T(System).out}" />
</bean>
</beans>
方法二。使用json
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sia.knights.BraveKnight;
import sia.knights.Knight;
import sia.knights.Quest;
import sia.knights.SlayDragonQuest;
@Configuration
public class KnightConfig {
@Bean
public Knight knight() {
return new BraveKnight(quest());
}
@Bean
public Quest quest() {
return new SlayDragonQuest(System.out);
}
}
两者完全等价
使用。
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
import sia.knights.config.KnightConfig;
public class KnightMain {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext contextXml =
new ClassPathXmlApplicationContext(
"META-INF/spring/knight.xml");
AnnotationConfigApplicationContext contextJava = new AnnotationConfigApplicationContext(KnightConfig.class);
Knight knight = contextXml.getBean(Knight.class);
knight.embarkOnQuest();
contextXml.close();
}
}
将contextJava完全替换即可运行,如果多个配置类。用,分隔
JAVA切面(aop, aspect-oriented programming)
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="knight" class="sia.knights.BraveKnight">
<constructor-arg ref="quest" />
</bean>
<bean id="quest" class="sia.knights.SlayDragonQuest">
<constructor-arg value="#{T(System).out}" />
</bean>
<bean id="minstrel" class="sia.knights.Minstrel">
<constructor-arg value="#{T(System).out}" />
</bean>
<aop:config>
<aop:aspect ref="minstrel">
<aop:pointcut id="embark"
expression="execution(* *.embarkOnQuest(..))"/>
<!-- 这里定义了一个切面minstrel, 在方法 embarkOnQuest 之前和之后。分别执行singBeforeQuest和singAfterQuest-->
<aop:before pointcut-ref="embark"
method="singBeforeQuest"/>
<!-- System.out是一个PrintStream -->
<aop:after pointcut-ref="embark"
method="singAfterQuest"/>
</aop:aspect>
</aop:config>
</beans>
第一章结束