简体   繁体   English

我可以在@resouce中使用其他变量名称吗

[英]Can i use different variable name with @resouce

It might be very basic question but having NPE so want to make sure 这可能是一个非常基本的问题,但是拥有NPE,因此请确保

do i have to use same resource name for variable or can be different when injected? 我必须为变量使用相同的资源名称还是注入时可以不同?

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

or can be 或者可以是

@Resource(name='foo')

private X fooxx;

i am using second case where instance name is different from resource name but getting NPE 我正在使用第二种情况,其中实例名称与资源名称不同,但是得到了NPE

Comment is correct this should work .... ensure the types are correct but the issue is probably something else. 评论是正确的,这应该可以..确保类型正确,但是问题可能是其他原因。 According to Spring docs on @Resource ... 根据@Resource上的Spring文档 ...

3.9.5 @Resource Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods. 3.9.5 @Resource Spring还支持在字段或bean属性设置器方法上使用JSR-250 @Resource批注进行注入。 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. 这是Java EE 5和6中的常见模式,例如在JSF 1.2托管Bean或JAX-WS 2.0端点中。 Spring supports this pattern for Spring-managed objects as well. Spring也为Spring管理的对象支持此模式。
@Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. @Resource具有名称属性,默认情况下,Spring将该值解释为要注入的Bean名称。 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. 如果未明确指定名称,则默认名称是从字段名称或setter方法派生的。 In case of a field, it takes the field name; 如果是字段,则以字段名称为准; in case of a setter method, it takes the bean property name. 在使用setter方法的情况下,它采用bean属性名称。 So the following example is going to have the bean with name "movieFinder" injected into its setter method: 因此,以下示例将把名称为“ movieFinder”的bean注入其setter方法中:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM