【发布时间】:2016-07-04 00:15:48
【问题描述】:
我正在使用 Spring Boot 实现休息服务。实体类在单独的包中定义。所以我在 Application.java 中添加了 Component 注释。
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.mdacc.rists.cghub.model")
@EnableJpaRepositories(basePackages = "org.mdacc.rists.cghub.model")
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
}
这是我的控制器类:
// SeqController.java
@RestController
public class SeqController {
@Autowired
private SeqService seqService;
@RequestMapping(
value = "/api/seqs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<SeqTb>> getSeqs() {
List<SeqTb> seqs = seqService.findAll();
return new ResponseEntity<List<SeqTb>>(seqs, HttpStatus.OK);
}
}
我还创建了一个扩展 JPARepository 的 JPA 数据存储库,我在其中添加了自定义查询代码。
// SeqRepository.java
@Repository
public interface SeqRepository extends JpaRepository<SeqTb, Integer> {
@Override
public List<SeqTb> findAll();
@Query("SELECT s FROM SeqTb s where s.analysisId = :analysisId")
public SeqTb findByAnalysisId(String analysisId);
}
下面是实现服务接口的servicebean类
// SeqServiceBean.java
@Service
public class SeqServiceBean implements SeqService {
@Autowired
private SeqRepository seqRepository;
@Override
public List<SeqTb> findAll() {
List<SeqTb> seqs = seqRepository.findAll();
return seqs;
}
public SeqTb findByAnalysisId(String analysisId) {
SeqTb seq = seqRepository.findByAnalysisId(analysisId);
return seq;
}
}
当我启动应用程序并在浏览器中输入以下 url "http://localhost:8080/api/seqs" 时,出现 404 错误。我错过了什么?
编辑#1: 我决定取出 JPA 存储库的东西并将控制器类更改为以下内容:
@RestController
//@RequestMapping("/")
public class SeqController {
private static BigInteger nextId;
private static Map<BigInteger, Greeting> greetingMap;
private static Greeting save(Greeting greeting) {
if(greetingMap == null) {
greetingMap = new HashMap<BigInteger, Greeting>();
nextId = BigInteger.ONE;
}
greeting.setId(nextId);
nextId = nextId.add(BigInteger.ONE);
greetingMap.put(greeting.getId(), greeting);
return greeting;
}
static {
Greeting g1 = new Greeting();
g1.setText("Hello World!");
save(g1);
Greeting g2 = new Greeting();
g1.setText("Hola Mundo!");
save(g2);
}
@RequestMapping(
value = "/api/greetings",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Greeting>> getGreetings() {
Collection<Greeting> greetings = greetingMap.values();
return new ResponseEntity<Collection<Greeting>>(greetings, HttpStatus.OK);
}
}
当我启动应用程序并在浏览器中输入“localhost:8080/api/greetings”时,我仍然得到 404。
【问题讨论】:
-
您的 application.properties 中是否设置了内容根路径?你也介意分享一下吗?
-
@shahshi15 我的application.properties中只有以下几行:
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://mdarisrac02d:3306/pancancer spring.datasource.username=user spring.datasource.password=pass spring.jpa.hibernate.ddl-auto=update如何设置内容根路径?
标签: java rest spring-boot spring-data-jpa