【问题标题】:Spring loads component before the needed beanSpring 在需要的 bean 之前加载组件
【发布时间】:2014-11-14 15:24:02
【问题描述】:

我的 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 App 启动项目时,UserRepo 构造函数的文本显示在控制台输出上 bean 的文本之前。事实上,变量 ldapTemplate 为 null,当然会导致异常。

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

【问题讨论】:

  • 您是否尝试在构造函数中使用ldapTemplate?
  • 我不清楚@DependsOn 将如何提供帮助。您在哪里看到 ldapTemplate 为 null?

标签: java spring


【解决方案1】:

使用@DependsOn注解来控制bean的初始化顺序。

【讨论】:

  • 您能解释一下使用@DependsOn 将如何修复变量 ldapTemplate 是null?
  • 问题是:“如何让 bean 实例化在组件实例化之前发生,以便 ldapTemplate 的自动装配起作用?”。可以使用@DependsOn 来完成。
  • 让我用重复这个问题,所以ldapTemplate 的自动装配工作。您如何解释 autowiring ldapTemplate 不起作用,而使用 @DependsOn 会使其起作用?
  • 我在上面代码中没有显示的另一个函数中使用了 ldapTemplate。由于 ldaptemplate 为空,因此使用此函数总是引发空指针异常。很清楚,因为 config-bean 是在 ldaptemplate 所在的类实例化之后加载的。因此,UserRepo 类上方的“@DependsOn("LDAP_TEMPLATE_BEAN")”解决了这个问题。
  • @Paul 否。请提供您所描述内容的可重现示例。只是 bean A 有一个 B 类型的 @Autowired 字段,这意味着 A 依赖于 B,并且 B 必须在 A 之前创建。@DependsOn 添加 nothing。
【解决方案2】:

您似乎认为一个 bean 可以在另一个 bean 对象被初始化之前被注入到该对象中。 Spring 需要先实例化您的 bean 类(调用其构造函数),然后才能注入任何字段。

一种选择是使用构造函数注入

@Autowired
public UserRepo(LdapTemplate ldapTemplate) {

或者将构造函数中的代码移到@PostConstruct注解的方法中

@PostConstruct
public void init() {
    // will get invoked after all injections
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 2015-12-18
  • 2013-07-07
  • 1970-01-01
相关资源
最近更新 更多