如何让 Spring 在 属性 引用中选择一个子类?
How to make Spring to pick a subclass in a property reference?
我正在尝试在 Spring 网络应用程序中使用专门的子程序class 进行测试。
应用程序上下文 xml 文件通过完全限定的 class 名称引用一些 bean 属性中的 class,如下所示:
<bean id="blahblah" class="x.y.z.Blah">
<property name="myFooAttribute" ref="x.y.z.Foo"/>
</bean>
并且我想实例化并使用 x.y.z.Bar
而不是 x.y.z.Foo
,在任何使用它的地方。
在我的测试中,我使用了基于 Java 的配置并导入了 XML 配置(我真的不想弄得太多的旧东西),因为它感觉更自然我将修补东西并使用内联声明的模拟。
@Configuration
@ImportResource({
"classpath:applicationContext-common.xml",
"classpath:app-servlet.xml"
})
static class TestConfig {
static class Bar extends Foo {
//some stuff overridden here
}
}
如何让所有引用 x.y.z.Foo
的地方都使用我的 Bar
class?最好不要更改 xml 文件...
创建一个名为 class 的 bean,您正试图覆盖它。它可以在 Java 样式配置中使用 Bean
注释来实现。
@Configuration
@ImportResource({
"classpath:applicationContext-common.xml",
"classpath:app-servlet.xml"
})
static class TestConfig {
static class Bar extends Foo {
//some stuff overridden here
}
private Bar myTestBar = new Bar();
@Bean(name="x.y.z.Foo")
public Foo getFoo() {
return myTestBar;
}
}
我正在尝试在 Spring 网络应用程序中使用专门的子程序class 进行测试。
应用程序上下文 xml 文件通过完全限定的 class 名称引用一些 bean 属性中的 class,如下所示:
<bean id="blahblah" class="x.y.z.Blah">
<property name="myFooAttribute" ref="x.y.z.Foo"/>
</bean>
并且我想实例化并使用 x.y.z.Bar
而不是 x.y.z.Foo
,在任何使用它的地方。
在我的测试中,我使用了基于 Java 的配置并导入了 XML 配置(我真的不想弄得太多的旧东西),因为它感觉更自然我将修补东西并使用内联声明的模拟。
@Configuration
@ImportResource({
"classpath:applicationContext-common.xml",
"classpath:app-servlet.xml"
})
static class TestConfig {
static class Bar extends Foo {
//some stuff overridden here
}
}
如何让所有引用 x.y.z.Foo
的地方都使用我的 Bar
class?最好不要更改 xml 文件...
创建一个名为 class 的 bean,您正试图覆盖它。它可以在 Java 样式配置中使用 Bean
注释来实现。
@Configuration
@ImportResource({
"classpath:applicationContext-common.xml",
"classpath:app-servlet.xml"
})
static class TestConfig {
static class Bar extends Foo {
//some stuff overridden here
}
private Bar myTestBar = new Bar();
@Bean(name="x.y.z.Foo")
public Foo getFoo() {
return myTestBar;
}
}