javascript
java编程中的di是什么_java-在Spring IoC / DI中使用@Component注释对接口...
在Spring類中,通常使用@Component注釋接口,特別是對于某些Spring構造型注釋:
package org.springframework.stereotype;
...
@Component
public @interface Service {...}
要么 :
package org.springframework.boot.test.context;
...
@Component
public @interface TestComponent {...}
@Component未聲明為繼承的注釋:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {...}
但是無論如何,在加載上下文期間,Spring都會通過考慮候選類中聲明的注釋的層次結構來發(fā)現(xiàn)bean.
在org.springframework.boot.BeanDefinitionLoader類(包含在Spring Boot依賴項中)中,該類從基礎源加載Bean定義,您可以看到一個示例
Spring用于在注釋的整個層次結構中檢索注釋的org.springframework.core.annotation.AnnotationUtils.findAnnotation():
class BeanDefinitionLoader {
...
private boolean isComponent(Class> type) {
// This has to be a bit of a guess. The only way to be sure that this type is
// eligible is to make a bean definition out of it and try to instantiate it.
if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
return true;
}
// Nested anonymous classes are not eligible for registration, nor are groovy
// closures
if (type.getName().matches(".*\$_.*closure.*") || type.isAnonymousClass()
|| type.getConstructors() == null || type.getConstructors().length == 0) {
return false;
}
return true;
}
...
}
具體來說,這意味著由于@Service注釋本身已使用@Component進行注釋,因此Spring將考慮使用@Service注釋的候選類作為實例化的bean.
因此,您的猜測是正確的:
Classes that implement such interface will be treated as components as
well.
但這僅適用于Java注釋的接口(例如@Service),不適用于普通接口.
對于Spring類,這種方式是有意義的(例如,豐富實際的構造型),但對于您自己的bean,將@Component用作接口而不是實現(xiàn)將不起作用,并且?guī)淼谋状笥诶?#xff1a;
>它以同樣的方式破壞了首先是合同的接口的目的.它將其耦合到Spring,并假設您將始終擁有該類的單個實現(xiàn).在這種情況下,為什么要使用接口?
>它將類的讀取分散在兩個位置,而接口不需要任何Spring構造型.
總結
以上是生活随笔為你收集整理的java编程中的di是什么_java-在Spring IoC / DI中使用@Component注释对接口...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星 One UI 6 丰富相机精细度选
- 下一篇: js清除添加的下拉框html,Html下