我在spring-boot应用程序中使用来自spring-hateoas的ResourceAssemblerSupport
我已经创建了如下汇编程序:
public class MemberResourceAssembler extends ResourceAssemblerSupport<Member, MemberResource>{
public MemberResourceAssembler(Class<?> controllerClass, Class<MemberResource> resourceType) {
super(controllerClass, resourceType);
}
@Override
public MemberResource toResource(Member member) {
MemberResource memberResource=new MemberResource();
memberResource.setStatus(member.getStatus());
memberResource.setHeight(member.getHeight());
memberResource.setIs_veg(member.getIs_veg());
memberResource.setRace(member.getRace());
memberResource.setWeight(member.getWeight());
return memberResource;
}
}
和资源类如下:
public class MemberResource extends ResourceSupport implements Serializable{
//relevant code here
}
域类如下:
@Document(collection="Member")
public class Member {
//relevant code here
}
存储库类如下:
public interface MemberRepository extends PagingAndSortingRepository<Member,Integer> {
Page<Member> findByStatusContainsIgnoreCase(@Param("q") String status, Pageable pageable);
}
现在我想在我的控制器中使用如下:
@RestController
@RequestMapping("/members")
public class MemberController {
@Autowired
private MemberRepository memberRepository;
@Autowired
private MemberResourceAssembler assembler;
@RequestMapping(value = "/search", method = RequestMethod.GET)
public PagedResources<MemberResource> search(@RequestParam("status") String status, @PageableDefault Pageable pageable,
PagedResourcesAssembler<Member> pagedAssembler) {
Page<Member> members = memberRepository.findByStatusContainsIgnoreCase(status, pageable);
return pagedAssembler.toResource(members, assembler);
}
}
我得到以下异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sg.resources.MemberResourceAssembler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
使用spring-hateoas版本0.19.0.RELEASE.All的依赖关系来自Spring Boot 1.3.0的启动器.RELEASE
Controller类的父包中有一个spring boot Application类。存储库上的Autowire注释工作正常。
答案 0 :(得分:1)
您的free(3)
应注明为MemberResourceAssembler
,以便将其用于自动装配。
答案 1 :(得分:0)
我在Application.class中添加了一个bean定义来解决问题
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public MemberResourceAssembler memberResourceAssembler() {
return new MemberResourceAssembler(MemberController.class, MemberResource.class);
}
}