简体   繁体   English

注释:方法与变量

[英]Annotations: methods vs variables

I was always sure (don't know why) that it's better to add annotations to variables, but while browsing the Hibernate doc http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection I noticed they tend to annotate the methods. 我总是确定(不知道为什么)最好在变量中添加注释,但在浏览Hibernate文档时http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity -hibspec-collection我注意到他们倾向于注释方法。 So should I put my annotations before methods, like this: 所以我应该在方法之前添加注释,如下所示:

@Entity
public class Flight implements Serializable {
private long id;

@Id @GeneratedValue
public long getId() { return id; }

public void setId(long id) { this.id = id; }
}  

Or is it better to do it like this: 或者这样做更好:

@Entity
public class Flight implements Serializable {
@Id @GeneratedValue
private long id;

public long getId() { return id; }

public void setId(long id) { this.id = id; }
}  

Or maybe there's no difference? 或者也许没有区别?

As Péter points out, you need to pick one style and stick with it, since the style adopted for the @Id annotation will be used for everything. 正如Péter指出的那样,你需要选择一种风格并坚持下去,因为@Id注释所采用的风格将用于所有事物。

Beyond that, it's simply a matter of taste. 除此之外,它只是一个品味问题。 Both options work, so go for the one you prefer. 这两个选项都有效,所以选择你喜欢的选项。 Some people prefer that Hibernate injects via methods, so that they can change the implementation subtly if they need to. 有些人更喜欢Hibernate通过方法注入,以便他们可以根据需要巧妙地改变实现。 I prefer injecting via fields, since I find it cumbersome to have to expose all properties via getter/setter methods (7 lines vs 1 line) when in 99.9% of the times they're going to work as simple variables (and in any case I can switch the annotation style if/when I need to write custom setter functionality anyway). 我更喜欢通过字段注入,因为我发现通过getter / setter方法(7行对1行)暴露所有属性很麻烦,因为在99.9%的时间它们将作为简单变量工作(并且在任何情况下)如果/当我需要编写自定义setter功能时,我可以切换注释样式)。

There are no performance or functionality differences between the two, so choose whichever you prefer (or perhaps more importantly, whichever your team/tools prefer). 两者之间没有性能或功能差异,因此请选择您喜欢的(或者更重要的是,您的团队/工具更喜欢哪个)。

With the @Id annotation, there is a difference: if it is on the getter, Hibernate tries to get/set all class members via their regular getters/setters, while if it is on the member variable, Hibernate will access all the member variables directly. 使用@Id注释,有一个区别:如果它在getter上,Hibernate尝试通过常规getter / setter获取/设置所有类成员,而如果它在成员变量上,Hibernate将访问所有成员变量直。

In other words, you can't mix styles within the same entity. 换句话说,您不能在同一实体中混合样式。

It depends on the annotation. 这取决于注释。

Very generally speaking, if the entity has the standard getters/setters which match the field names then there isn't much of a difference. 一般来说,如果实体具有与字段名称匹配的标准getter / setter,则没有太大区别。 I tend to annotate fields when given the choice, just because I find burying the annotations down with the methods to be harder to read. 我倾向于在给出选择时注释字段,只是因为我发现将注释埋没在方法中以便更难阅读。

It's sometimes handy to be able to chose where to put them, especially when a field is not exposed publicly. 能够选择放置它们的位置有时候很方便,特别是当场地没有公开曝光时。 It's not very common to have private getter/setter, so it's useful to be able to put annotation on the field. 私有getter / setter并不常见,所以能够在字段上添加注释是很有用的。

It also sometimes give a bit of flexibility to play with the external/internal data representation. 它有时也可以灵活地使用外部/内部数据表示。 Here is an example that is a bit silly, but I've used a similar trick a few times ( here and here ): 这是一个有点傻的例子,但我已经使用了几次类似的技巧( 这里这里 ):

@Column(...)
private String email;

public String getAlias() { ... split email and return the part before @ ... }
public void setAlias( String alias ) { ... change the part before the @ ... }

public String getHost() { ... split email and return the part after @ ... }
public void setHost(String host) { ... change the part after the @... }

Generally speaking, I tend to put them on the field, I find the code more readable. 一般来说,我倾向于将它们放在字段上,我发现代码更具可读性。 But it's mostly a question of taste. 但这主要是品味问题。 The only rule to enforce is to be consitent! 强制执行的唯一规则就是坚持!

Yeah, and i'd go against annotating stuff too much. 是的,而且我反对过多注释。 It's nice when you're doing reflection or something like that, but i don't think that anybody wants to read annotations just because somebody thought to replace comments with them. 当你做反思或类似事情时,这很好,但我不认为有人想读取注释只是因为有人想用它们取代注释。

I strongly recommend use annotation on top of variables rather than using annotation on methods. 我强烈建议在变量之上使用注释,而不是在方法上使用注释。 This is NOT matter of taste. 这不是味道。 This is MANDATORY if you want to declare USER class which implements UserDetails from Spring Security. 如果要声明从Spring Security实现UserDetails的USER类,这是强制性的。 So following code will work and that is the only way. 所以下面的代码将起作用,这是唯一的方法。

@Entity
class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany
    private List<UserRole> roles;

    //....Setters and Getters..........
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }

If you place all annotations at function getters, without mapping @OneToMany or @ManyToMany ...it will work but if you need to use those relationship then Hibernate will break. 如果将所有注释放在函数getter中,而不映射@OneToMany@ManyToMany ......它会起作用,但是如果你需要使用这些关系,那么Hibernate将会中断。 I think Hibernate already use annotation on top of variable so it doesn't like annotation of top of functions for consistent reason. 我认为Hibernate已经在变量之上使用了注释,因此出于一致的原因它不喜欢函数顶部的注释。

Therefore, stick to what is conventional of the framework, you won't have your codes breaks down later. 因此,坚持框架的传统,你不会在以后破坏你的代码。

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

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