[英]Spring boot injection of inherited class
我正在開發一個Java核心庫,將更改保持在最低限度,它包含一個Foo類,其中Foo由spring rest接口使用,並自動連接到rest接口。
我必須擴展Foo來覆蓋在Foo.init()上調用的方法之一,以稍微更改啟動方式。
我的FooExtend是從項目中的另一個類自動連接的,我希望讓這兩個引用相同的對象FooExtend對象,但此刻我得到了一個Foo對象和一個FooExtend。 我該如何解決? 下面的例子
@Component
public class Foo{
@PostConstruct
private void init() {
startStuff();
}
protected void startStuff(){
//Stuff done here
}
}
@Component
public class FooExtend extends Foo{
@PostConstruct
private void init() {
//Nothing is done here
}
@Override
protected void startStuff(){
//Different altered stuff is done here
}
}
嘗試從掃描中排除Foo類
@ComponentScan(value = {'your.package.here'}, excludeFilters = {
@ComponentScan.Filter(classes = { Foo.class })
})
根據您的要求,有2種可能的答案:
1)您想在Spring上下文中注冊Foo和FooExtend。 在這種情況下,可以使用@Qualifier批注注入一個或另一個實例:
@Autowired
@Qualifier("fooExtend")
Foo foo;
2)您只想在Spring上下文中注冊FooExtend。
@ComponentScan(value = {'your.package.here'}, excludeFilters = {
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class))
}
但是,要求Foo和FooExtend在不同的程序包中,以便上述過濾器不排除FooExtend。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.