Spring 只能注册constructor beans?
Spring can only register contructor beans?
假设我有一个 class A
(@Component) 和一个 class B
(@Component)。 Class A
需要 B
的实例。如果我使用@Autowired 将 class B
作为 A 中的字段,即使 Spring 会找到 B
组件(通过 @ComponentScan),class A
字段将为空。但是,如果我将 B
作为参数放在 A
的构造函数中,并使用 @Autowired 注释构造函数,它将完美地工作。
有什么方法可以从 A
的构造函数中排除 B
吗?
正如@LuiggiMendoza 提到的:创建一个@PostConstruct 方法很简单:您应该只用@PostConstruct 注释您的方法:
public class A {
@PostConstruct
void init(){
//do smth here
}
}
或者如果您使用 XML 配置,您可以将 init-method
参数添加到您的 bean 定义中。
假设我有一个 class A
(@Component) 和一个 class B
(@Component)。 Class A
需要 B
的实例。如果我使用@Autowired 将 class B
作为 A 中的字段,即使 Spring 会找到 B
组件(通过 @ComponentScan),class A
字段将为空。但是,如果我将 B
作为参数放在 A
的构造函数中,并使用 @Autowired 注释构造函数,它将完美地工作。
有什么方法可以从 A
的构造函数中排除 B
吗?
正如@LuiggiMendoza 提到的:创建一个@PostConstruct 方法很简单:您应该只用@PostConstruct 注释您的方法:
public class A {
@PostConstruct
void init(){
//do smth here
}
}
或者如果您使用 XML 配置,您可以将 init-method
参数添加到您的 bean 定义中。