Spring 自動依賴注入優化(autowire-candidate)
阿新 • • 發佈:2019-02-08
自動依賴注入大大簡化了我們的工作量,但是也有缺陷,如果一個介面有多個實現類,我們該注入哪一個呢?一種方法是設定其中一個bean不參與自動注入。
package shangbo.spring.example38;
public interface MessageService {
String getMessage();
}
package shangbo.spring.example38; public class MessageServiceDBImpl implements MessageService { public String getMessage() { return "This message from database"; } }
package shangbo.spring.example38;
public class MessageServiceFileImpl implements MessageService {
public String getMessage() {
return "This message from file";
}
}
package shangbo.spring.example38; public class MessagePrinter { private MessageService service; public void setService(MessageService service) { this.service = service; } public void printMessage() { System.out.println(service.getMessage()); } }
<?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" default-autowire="byType"> <!-- 全域性設定自動注入方式 --> <!-- 兩個物件繼承自同一介面 autowire-candidate="false" 表示該物件不參與自動注入 --> <bean class="shangbo.spring.example38.MessageServiceDBImpl" autowire-candidate="false" /> <bean class="shangbo.spring.example38.MessageServiceFileImpl"/> <bean class="shangbo.spring.example38.MessagePrinter"/> </beans>
package shangbo.spring.example38;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
// 例項化 Spring IoC 容器
ApplicationContext context = new ClassPathXmlApplicationContext("example.xml", MessagePrinter.class);
// 從容器中獲得 MessagePrinter 的例項
MessagePrinter printer = context.getBean(MessagePrinter.class);
// 使用物件
printer.printMessage();
}
}
我們也可以設定全域性設定哪些物件不引數自動注入。
<?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"
default-autowire="byType"
default-autowire-candidates="messageServiceDBImpl">
<!--
全域性設定名為 messageServiceDBImpl 不參與自動注入
可以指定多個值,逗號分隔
-->
<!--
兩個物件繼承自同一介面
-->
<bean id = "messageServiceDBImpl" class="shangbo.spring.example39.MessageServiceDBImpl"/>
<bean class="shangbo.spring.example39.MessageServiceFileImpl"/>
<bean class="shangbo.spring.example39.MessagePrinter"/>
</beans>
–
– 聲 明:轉載請註明出處
– Last Updated on 2017-05-25
– Written by ShangBo on 2017-05-25
– End