Java Spring在所需bean之前加载组件
我的Spring项目中有一个基于注释的配置类:Java Spring在所需bean之前加载组件,java,spring,Java,Spring,我的Spring项目中有一个基于注释的配置类: @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Bean(name = "LDAP_TEMPLATE_BEAN") public LdapTemplate configLdapTemplate() { System.out.println("BEAN
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean(name = "LDAP_TEMPLATE_BEAN")
public LdapTemplate configLdapTemplate() {
System.out.println("BEAN LDAP LOADED");
LdapContextSource lcs = new LdapContextSource();
lcs.setUrl("ldap://127.0.0.1:33389/");
// lcs.setUserDn(BASE_DN);
lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
// lcs.setAnonymousReadOnly(true);
lcs.afterPropertiesSet();
return new LdapTemplate(lcs);
}
以及需要定义bean的组件类:
@Component
public class UserRepo {
@Autowired
private LdapTemplate ldapTemplate;
public UserRepo() {
System.out.println("UserRepo created");
当我以springboot应用程序的形式启动项目时,UserRepo构造函数的文本显示在控制台输出的bean文本之前。事实上,变量ldapTemplate为null,当然会导致异常
如何让bean实例化在组件实例化之前发生,这样ldapTemplate的自动连接就可以工作?使用注释来控制bean初始化顺序。您似乎认为可以在初始化另一个bean对象之前将bean注入该对象。Spring需要先实例化bean类(调用其构造函数),然后才能注入任何字段 一种选择是使用构造函数注入
@Autowired
public UserRepo(LdapTemplate ldapTemplate) {
或者将构造函数中的代码移动到带注释的@PostConstruct
方法
@PostConstruct
public void init() {
// will get invoked after all injections
}
您是否试图在构造函数中使用
ldapTemplate
?我不清楚@DependsOn
在这里有什么帮助。您在哪里看到ldapTemplate
为null
?您能否解释一下使用@DependsOn
将如何修复变量ldapTemplate isnull
?问题是:“我如何让bean实例化发生在组件实例化之前,这样ldapTemplate的自动连接就可以工作?”。可以用@DependsOn完成。让我用重复这个问题,这样ldapTemplate
的自动连接就可以工作了。您如何解释自动布线ldapTemplate
不起作用,使用@DependsOn
将使其起作用?我在上面代码中未显示的另一个功能中使用了ldapTemplate。由于ldaptemplate为null,因此此函数的使用始终引发nullpointer异常。很明显,因为配置bean是在ldaptemplate所在的类实例化之后加载的。因此,UserRepo类上方的“@DependsOn”(“LDAP\u TEMPLATE\u BEAN”)修复了该问题。@Paul否。请提供一个可复制的示例来说明您所描述的内容。事实上,一个bean a有一个类型为B的@Autowired
字段,这意味着a依赖于B,而B必须在a之前创建。@DependsOn
不添加任何内容。我尝试了这个方法,但似乎不起作用。我把问题贴在这里。