2017-04-03 649 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自动装载您的孩子,而无需您直接给孩子附加注释。