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.
Init array with fields injected with @Resource
-
21-07-2023 - |
Question
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!
Solution
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow