سؤال

I have Spring-managed app and try to access injected reources from array:

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;

@Service("serviceA")
class A {

    @Resource
    private HeaderLevelValidator defaultHeaderLevelValidator;

    @Resource
    private HeaderLevelValidator headerLevelValidator;

    /** Validators specific for Storefront. */
    private final Collection<HeaderLevelValidator> HEADER_BEAN_NAMES = Arrays.asList(defaultHeaderLevelValidator,
            headerLevelValidator);

    public Collection<HeaderLevelValidator> getHeaderValidators()
    {
        return HEADER_BEAN_NAMES;
    }

}

I try to access my list at Runtime with getHeaderValidators() but got list of nulls {null, null}. Why? What is correct way to define list of injected resources?

Thanks in advance!

هل كانت مفيدة؟

المحلول

The problem is that HEADER_BEAN_NAMES is being initialized before your beans are being injected. Field injection occurs after object instantiation and initialization. Try moving the initialization to a method annotated with @PostConstruct, or if you want to keep HEADER_BEAN_NAMES final, use constructor injection instead.

نصائح أخرى

Initialize post construction.

private Collection<HeaderLevelValidator> HEADER_BEAN_NAMES;

@PostConstruct
public void init()
{
   HEADER_BEAN_NAMES = Arrays.asList(defaultHeaderLevelValidator,
        headerLevelValidator);
}

The init() method will be called after the managed bean is constructed by Spring. Note that HEADER_BEAN_NAMES cannot be final as it is initialized post construction.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top