为什么当我使用@autowired服务初始化对象实例字段时,它们仍然为空?

问题描述 投票:1回答:2

最近,我遇到了如下所示的问题:

@Service
public DemoServiceImpl implements DemoService {

    @Autowired
    private FooService fooService;

    // Get NullPointerException here because fooService was still null.
    privare Map<String, String> demoMap = fooService.getDemoMap(); 

    // ... Remainder omitted
}

有人可以解释我何时发生了字段依赖注入吗?为什么我调用fooService初始化demoMap时仍为null?无论如何,一直欢迎您的回答!

这里是FooServiceFooServiceImpl

public FooService {
    Map<String, String> getDemoMap();
}
@Service
public FooServiceImpl implements FooService {

    @Autowired
    private FooRepository fooRepository;

    @Override public Map<String, String> getDemoMap() {
        // Invoke fooRepository to do somethings
        return Collections.emptyMap();
    }

}
java spring nullpointerexception null autowired
2个回答
0
投票

实例字段初始化发生在构造函数执行之前。

对于带@Autowired注释的字段,Spring将实例化bean,然后注入依赖项。因此,在访问字段初始值设定项中的fooService时,它仍然为null且尚未注入。

要解决这个问题,您可以像这样使用@PostConstruct

@PostConstruct 
public void initialize() {
    demoMap = fooService.getDemoMap();
}

此方法将在构造方法之后和注入依赖项之后执行。


0
投票

也许您不应该使用FooServiceImpl,直接将FooService与@Service批注一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.