gpt4 book ai didi

java - 我可以对 @resouce 使用不同的变量名吗

转载 作者:行者123 更新时间:2023-12-02 10:22:45 25 4
gpt4 key购买 nike

这可能是非常基本的问题,但有 NPE,所以想确定一下

我是否必须为变量使用相同的资源名称,或者注入(inject)时可以不同?

@Resource(name='foo')
private X foo;

或者可以

@Resource(name='foo')

private X fooxx;

我正在使用第二种情况,其中实例名称与资源名称不同,但得到 NPE

最佳答案

评论是正确的,这应该可以工作......确保类型正确,但问题可能是其他原因。根据Spring docs on @Resource ...

3.9.5 @Resource Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods. This is a common pattern in Java EE 5 and 6, for example in JSF 1.2 managed beans or JAX-WS 2.0 endpoints. Spring supports this pattern for Spring-managed objects as well.
@Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics, as demonstrated in this example:

public class SimpleMovieLister {

private MovieFinder movieFinder;

@Resource(name="myMovieFinder")
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}

If no name is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name. So the following example is going to have the bean with name "movieFinder" injected into its setter method:

关于java - 我可以对 @resouce 使用不同的变量名吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54208433/

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