目錄結構

沒有使用 spring 的構造器注入形式:

`DeclareSpringComponent`是用于 spring 的,暫時不理。
`ConstructorInjection`是普通構造器注入,`Dependency`是依賴項。通過在構造器中提供依賴項,實現基于構造器的依賴注入。
~~~
// 注意 @Autowired 只能用于其中一個構造器自動注入
~~~
---
接著有個三個spring應用類:

其中 `DeclareSpringComponents` 就是演示使用 spring 構造器注入而已。
~~~
public class DeclareSpringComponents {
public static void main(String... args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring/app-context-annotation.xml");
ctx.refresh();
MessageProvider messageProvider = ctx.getBean("provider",
MessageProvider.class);
System.out.println(messageProvider.getMessage());
ctx.close();
}
}
~~~
對應的 xml 配置文件:
~~~
<!--省略 schema -->
<context:component-scan
base-package="com.apress.prospring5.ch3.annotated"/>
<bean id="message" class="java.lang.String"
c:_0="希望你會好好的 I hope that someone gets my message in a bottle"/>
<bean id="message2" class="java.lang.String"
c:_0="I know I won't be injected :("/>
~~~
上面配置文件掃描到 `com.apress.prospring5.ch3.annotated` 這個包下的 bean :
~~~
@Repository("provider")
public class ConfigurableMessageProvider implements MessageProvider {
private String message;
// 根據參數名來自動注入,構造器注入
@Autowired
public ConfigurableMessageProvider(String message) {
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
}
~~~
它對應的 `MessageProvider` 是:
~~~
@Repository("provider")
public class ConfigurableMessageProvider implements MessageProvider {
private String message;
// 根據參數名來自動注入,構造器注入
@Autowired
public ConfigurableMessageProvider(String message) {
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
}
~~~
---
接下來看看 `ConstructorConfusion` 這個類里邊演示了兩個構造器,spring 根據構造器的參數類型判斷應該注入那個 bean.
~~~
public class ConstructorConfusion {
private String someValue;
//兩個構造器注入,根據構造器參數的類型來判斷注入哪一個
public ConstructorConfusion(String someValue) {
System.out.println("ConstructorConfusion(String) called");
this.someValue = someValue;
}
public ConstructorConfusion(int someValue) {
System.out.println("ConstructorConfusion(int) called");
this.someValue = "Number: " + someValue;
}
public static void main(String... args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring/app-context-xml.xml");
ctx.refresh();
ConstructorConfusion cc = (ConstructorConfusion) ctx.getBean("constructorConfusion");
System.out.println(cc);
ctx.close();
}
public String toString() {
return someValue;
}
}
~~~
在 xml 配置文件里 bean 標簽指定構造器參數的類型,據此確定依賴注入的類型。
~~~
<bean id="provider"
class="com.apress.prospring5.ch3.xml.ConfigurableMessageProvider"
c:message="I hope that someone gets my message in a bottle"/>
<bean id="constructorConfusion"
class="com.apress.prospring5.ch3.xml.ConstructorConfusion">
<constructor-arg type="int">
<value>90</value>
</constructor-arg>
</bean>
~~~