【问题标题】:Spring Boot partially replacing autoconfigurationSpring Boot 部分替换自动配置
【发布时间】:2015-08-20 09:54:10
【问题描述】:

我一直在探索 Spring Boot (1.2.4) 以使用 H2 和 Jackson 创建一个简单的 RESTful 存储库。

与其他人一样,我注意到默认情况下,@Id 字段不在返回的 Json 中(如本问题所述:While using Spring Data Rest after migrating an app to Spring Boot, I have observed that entity properties with @Id are no longer marshalled to JSON)。

所以我想调整配置以包含它们。

但是我无法让它全部工作。

基本实体类:

@Entity
public class Thing {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id; //I want this to appear in the RESTful JSON

    private String someInformation;

    protected Thing(){};

    public String getSomeInformation() { return someInformation; }

    public void setSomeInformation(String someInformation) { this.someInformation = someInformation; }

}

基本仓库界面:

public interface ThingRepository extends PagingAndSortingRepository<Thing, Long> {    
    List<Thing> findBySomeInformation(@Param("SomeInformation") String someInformation);
}

简单的启动应用程序:

@ComponentScan
@EnableAutoConfiguration
public class Application {    
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }    
}

还有我的配置类:

@Configuration
public class RepositoryRestMvcConfig extends SpringBootRepositoryRestMvcConfiguration {     
    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Thing.class);
    }        
}

我可以通过使用 --debug 运行 Spring Boot(如 http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html 中所述)看到我的配置已找到,但似乎没有任何效果。

【问题讨论】:

  • 为 id 属性添加 getter/setter?
  • 如果你添加 getter 和 setter 就可以了

标签: spring spring-boot spring-data spring-restcontroller


【解决方案1】:

Jackson 处理类的 getter/setter,而不是成员变量本身。因此,要确保 id 在 JSON 中,只需为其添加一个 getter:

@Entity
public class Thing {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id; //I want this to appear in the RESTful JSON

    private String someInformation;

    protected Thing(){};

    //this is what is needed
    public long getId() { return id; }

    public String getSomeInformation() { return someInformation; }

    public void setSomeInformation(String someInformation) { this.someInformation = someInformation; }

}

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2018-09-09
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2017-12-11
    • 2015-02-24
    • 1970-01-01
    相关资源
    最近更新 更多