gpt4 book ai didi

java - Spring 在所需的 bean 之前加载组件

转载 作者:行者123 更新时间:2023-12-02 15:53:34 24 4
gpt4 key购买 nike

我的 Spring 项目中有一个基于注释的配置类:

@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");

当我作为 Spring Boot 应用程序启动项目时,UserRepo 构造函数的文本显示在控制台输出上的 bean 文本之前。事实上,变量 ldapTemplate 为 null,当然会导致异常。

如何让 bean 实例化发生在组件实例化之前,以便 ldapTemplate 的 Autowiring 起作用?

最佳答案

使用@DependsOn用于控制 bean 初始化顺序的注释。

关于java - Spring 在所需的 bean 之前加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26933286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com