2017-04-03 114 views
3

我有一個類的層次結構。我想用@Component來標記它們。我只想標記父類。我希望Spring也意味着孩子也是組件。但它沒有發生。在Spring中繼承@Component

我試圖使用自定義@InheritedComponent註釋類似於描述here。它不起作用。

我寫了一個單元測試。它失敗:"No qualifying bean of type 'bean.inherit.component.Child' available"。春天版本是4.3.7。

@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME) 
@Component 
@Inherited 
public @interface InheritedComponent {} 

@InheritedComponent 
class Parent { } 

class Child extends Parent { 
} 

@Configuration 
@ComponentScan(basePackages = "bean.inherit.component") 
class Config { 
} 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = Config.class) 
public class InheritComponentTest { 

    @Autowired 
    private Child child; 

    @Test 
    public void name() throws Exception { 
     assertNotNull(child); 
    } 
} 

回答

5

您可以爲此使用ComponentScan.Filter。

@ComponentScan(basePackages = "bean.inherit.component", 
includeFilters = @ComponentScan.Filter(InheritedComponent.class)) 

這將允許Spring自動裝載您的孩子,而無需您直接給孩子附加註釋。