我已经尝试了所有可能的方法,但我自己不喜欢我得到的解决方案。
我正在使用 Spring Framework 和 Thymeleaf。在我的实体类中,我将我的属性声明为私有,如下所示
public class Subscriber {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name= "firstname")
private String firstname;
@Column(name= "lastname")
private String lastname;
@Column(name= "email")
private String email;
public Subscriber(){
}
}
在 Thymeleaf 中,我正在使用:请从我的数据库中获取数据,如下所示:
<tr th:each="subscriber : ${subscribers}">
<td th:text="${subscriber.firstname} + ' ' + ${subscriber.lastname}"></td>
<td th:text="${subscriber.email}"></td>
当我运行代码时,我在运行时遇到以下错误:
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'firstname' cannot be found on object of type '' - maybe not public?
现在,如果我将修饰符更改为 public,一切正常,我的数据也会显示出来。但是,我认为这不是为实体建模的最佳方式。我需要警惕将来可能访问我的代码库的第三方,从而防止他们修改我的代码并对我造成损害。
因此,我需要任何更有经验的人的帮助,了解如何在无需将修饰符从私有更改为公共的情况下绕过它。
感谢任何帮助。
如果您可以通过将其从私有更改为公共来获得该属性,那么听起来您的吸气剂有问题。你应该在 Subscriber 类中检查你的 getters 和 setters。
如果 getter 是 getFirstName(),它将不起作用,因为类中的属性名称是“firstname”而不是 firstName。
@Entity
@Table(name= "subscribers")
public class Subscriber {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name= "firstname")
private String firstname;
@Column(name= "lastname")
private String lastname;
@Column(name= "email")
private String email;
public long getId(){
return this.id;
}
public void setId(long id){
this.id = id;
}
//This should not be getFirstName()
public String getFirstname(){
return this.firstname;
}
public void setFirstname(String fistname){
this.firstname = firstname;
}
//This should not be getLastName()
public String getLastname(){
return this.lastname;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getEmail(){
return this.email;
}
public void setEmail(String email){
this.email = email;
}
public Subscriber(){
}
}
在百里香中称这些:
<tr th:each="subscriber : ${subscribers}">
<td th:text="${subscriber.firstname} + ' ' + ${subscriber.lastname}"></td>
<td th:text="${subscriber.email}"></td>
我还没有测试过这些,但这些应该有用。
有点奇怪,如果你有公共领域范围,它会起作用。但是我看到的是你的表达不正确。
尝试使用
<td th:text="${subscriber.firstname + ' ' + subscriber.lastname}"></td>
Thymeleaf 在视图层使用 getter 方法。当你说
subscriber.firstName
时,它会调用subscriber.getFirstName()
。因此,在 public
类中有带有 Subscriber
访问修饰符的吸气剂。
我通过执行以下操作克服了这个问题:在主类中签署 getters 和 setters 方法!注意:如果您尝试使用 Lombok 进行签名,它很可能无法正常工作,所以我的意思是您必须对这些方法进行签名,而不是使用 lombok 在主类之上编写 Getter 和 Setter!