使 bean 的成员可用于自动装配
Make a member of a bean available for autowiring
@Component
class MultiProvider {
public Foo getFoo();
public Bar getBar();
}
@Component
class FooConsumer {
FooConsumer(Foo f);
}
我可以将 MultiProvider.getFoo()
自动连接到 FooConsumer
构造函数中吗..
- 不使
Foo
成为 bean 本身(例如,因为 Spring 不应该销毁它,因为这是 MultiProvider
的责任)
- 并且没有引入从
FooConsumer
到 MultiProvider
(或任何其他 class)的依赖项?
Spring 只能自动装配声明的 bean,可能的解决方法如下:
@Component
class FooConsumer {
private final Foo foo;
FooConsumer(MultiProvider multiProvider) {
// MultiProvider will be autowired by spring - constructor injection
this.foo = multiProvider.getFoo();
}
}
您可以通过 @Bean
在 MultiProvider
中注释 getFoo()
方法来实现这一点
@Component
class MultiProvider {
@Bean(destroyMethodName="cleanup") // HERE IS THE TRICK
public Foo getFoo();
public Bar getBar();
}
@Component
class FooConsumer {
FooConsumer(Foo f);
}
如果问题出在 spring 无法正确销毁它这一点,您可以将逻辑包含在 cleanup
声明的方法中,同时通过 @Bean
进行注释
public class Foo {
public void cleanup() {
// destruction logic
}
}
Note that @component and @configurable are more or less the same with
some subtle differences but in your case you can use @component if you don't
want to change it. More Info
您可以将它们包含在您的 Configuration
中。
@Configuration
class MyConfig {
@Bean
public MultiProvider getMP() {
return new MultiProvider() ;
}
@Bean
public Foo getFoo() {
return getMP(). getFoo();
}
}
不确定这是否违反了您的 'not a Bean itself' 规则。
@Component
class MultiProvider {
public Foo getFoo();
public Bar getBar();
}
@Component
class FooConsumer {
FooConsumer(Foo f);
}
我可以将 MultiProvider.getFoo()
自动连接到 FooConsumer
构造函数中吗..
- 不使
Foo
成为 bean 本身(例如,因为 Spring 不应该销毁它,因为这是MultiProvider
的责任) - 并且没有引入从
FooConsumer
到MultiProvider
(或任何其他 class)的依赖项?
Spring 只能自动装配声明的 bean,可能的解决方法如下:
@Component
class FooConsumer {
private final Foo foo;
FooConsumer(MultiProvider multiProvider) {
// MultiProvider will be autowired by spring - constructor injection
this.foo = multiProvider.getFoo();
}
}
您可以通过 @Bean
MultiProvider
中注释 getFoo()
方法来实现这一点
@Component
class MultiProvider {
@Bean(destroyMethodName="cleanup") // HERE IS THE TRICK
public Foo getFoo();
public Bar getBar();
}
@Component
class FooConsumer {
FooConsumer(Foo f);
}
如果问题出在 spring 无法正确销毁它这一点,您可以将逻辑包含在 cleanup
声明的方法中,同时通过 @Bean
public class Foo {
public void cleanup() {
// destruction logic
}
}
Note that @component and @configurable are more or less the same with some subtle differences but in your case you can use @component if you don't want to change it. More Info
您可以将它们包含在您的 Configuration
中。
@Configuration
class MyConfig {
@Bean
public MultiProvider getMP() {
return new MultiProvider() ;
}
@Bean
public Foo getFoo() {
return getMP(). getFoo();
}
}
不确定这是否违反了您的 'not a Bean itself' 规则。