2017-10-17 133 views
0

所以即时通讯刚刚开始使用弹簧启动,并尝试实施crud服务。我的代码主要来自本教程Spring Boot Rest API Example,我只是更改了变量名称。 我觉得我的所有问题都与启动弹簧引导等出,但现在我无法访问我的本地主机上的API。我希望有人能帮助我:)使用弹簧启动时无法访问REST API

我Application.java

package demo.app; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication(scanBasePackages= {"demo"}) 
public class App { 

    public static void main(String[] args) { 
    SpringApplication.run(App.class, args); 
    } 
} 

我的模型Game.java:

package demo.model; 


public class Game { 

private long id; 

private String name; 
private String genre; 
private String studio; 
private String publisher; 


public Game(long id, String name, String genre, String studio, String publisher) { 
    this.id = id; 
    this.name = name; 
    this.genre = genre; 
    this.studio = studio; 
    this.publisher = publisher; 
} 

public long getId() { 
    return id; 
} 
public void setId(long id) { 
    this.id = id; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public String getGenre() { 
    return genre; 
} 
public void setGenre(String genre) { 
    this.genre = genre; 
} 
public String getStudio() { 
    return studio; 
} 
public void setStudio(String studio) { 
    this.studio = studio; 
} 
public String getPublisher() { 
    return publisher; 
} 
public void setPublisher(String publisher) { 
    this.publisher = publisher; 
} 

@Override 
public String toString() { 
    return "Game [id=" + id + ", name=" + name + ", genre=" + genre + ", studio=" + studio + ", publisher=" 
      + publisher + "]"; 
    } 
} 

API的控制器RestApiController.java

package demo.app.controller; 

import java.util.List; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.http.HttpHeaders; 
import org.springframework.http.HttpStatus; 
import org.springframework.http.ResponseEntity; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.util.UriComponentsBuilder; 

import demo.model.Game; 
import demo.service.GameService; 
import demo.util.CostumErrorType; 


@RestController 
@RequestMapping("/api") 
public class RestApiController { 
public static final Logger logger = LoggerFactory.getLogger(RestApiController.class); 

@Autowired 
GameService gameService; // Service which will do all data retrieval/manipulation work 

//---------------Retrieve all games--------------------------------- 

@RequestMapping(value = "/game/", method = RequestMethod.GET) 
public ResponseEntity<List<Game>> listAllGames() { 
    List<Game> games = gameService.findAllGames(); 
    if(games.isEmpty()) { 
     return new ResponseEntity(HttpStatus.NO_CONTENT); 
     //TODO: vllt in HttpStatus.NOT_FOUND ändern 
    } 
    return new ResponseEntity<List<Game>>(games, HttpStatus.OK); 
} 

//---------------Retrieve Single Game--------------------------------- 


@RequestMapping(value = "/game/{id}", method = RequestMethod.GET) 
public ResponseEntity<?> getGame(@PathVariable("id") long id) { 
    logger.info("Fetching User with id {}", id); 
    Game game = gameService.findById(id); 
    if(game == null) { 
     logger.error("Game with id {} not found.", id); 
     return new ResponseEntity(new CostumErrorType("Game with id " + id + " not found"), HttpStatus.NOT_FOUND); 
    } 
    return new ResponseEntity<Game>(game, HttpStatus.OK); 
} 

//---------------Create a Game--------------------------------- 

@RequestMapping(value= "/game/", method = RequestMethod.POST) 
public ResponseEntity<?> createGame(@RequestBody Game game, UriComponentsBuilder ucBuilder){ 
    logger.info("Creating Game: {}", game); 

    if(gameService.isGameExist(game)) { 
     logger.error("Unable to create. A Game with name {} already exists.", game.getName()); 
     return new ResponseEntity(new CostumErrorType("Unable to create. A Game with name " + game.getName() + "already exists."), HttpStatus.CONFLICT);  
    } 
    gameService.saveGame(game); 

    HttpHeaders headers = new HttpHeaders(); 
    headers.setLocation(ucBuilder.path("/api/game/{id}").buildAndExpand(game.getId()).toUri()); 
    return new ResponseEntity<String>(headers, HttpStatus.CREATED); 
    } 
} 

服务接口GameService.java:

package demo.service; 

import java.util.List; 

import demo.model.Game; 

public interface GameService { 

    Game findById(long id); 

    Game findByName(String name); 

    void saveGame(Game game); 

    void updateGame(Game game); 

    void deleteGameByName(String name); 

    List<Game> findAllGames(); 

    void deleteAllGames(); 

    boolean isGameExist(Game game); 

} 

的Implentation它GameServiceImpl.java:

package demo.service; 

import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import java.util.concurrent.atomic.AtomicLong; 

import org.springframework.stereotype.Service; 

import demo.model.Game; 

@Service("gameService") 
public class GameServiceImpl implements GameService{ 

private static final AtomicLong counter = new AtomicLong(); 

private static List<Game> games; 

static { 
    games = populateDummyGames(); 
} 

public List<Game> findAllGames(){ 
    return games; 
} 

public Game findById(long id) { 
    for(Game game : games) { 
     if(game.getId() == id) { 
      return game; 
     } 
    } 
    return null; 
} 

public Game findByName(String name) { 
    for(Game game : games) { 
     if(game.getName().equalsIgnoreCase(name)) { 
      return game; 
     } 
    } 
    return null; 
} 

public void saveGame(Game game) { 
    game.setId(counter.incrementAndGet()); 
    games.add(game); 
} 

public void updateGame(Game game) { 
    int index = games.indexOf(game); 
    games.set(index, game); 
} 

public void deleteGameById(long id) { 

    for (Iterator<Game> iterator = games.iterator(); iterator.hasNext();) { 
     Game game = iterator.next(); 
     if (game.getId() == id) { 
      iterator.remove(); 
     } 
    } 
} 

public void deleteGameByName(String name) { 

    for (Iterator<Game> iterator = games.iterator(); iterator.hasNext();) { 
     Game game = iterator.next(); 
     if (game.getName().equalsIgnoreCase(name)) { 
      iterator.remove(); 
     } 
    } 
} 

public boolean isGameExist(Game game) { 
    return findByName(game.getName())!=null; 
} 

public void deleteAllGames() { 
    games.clear(); 
} 

private static List<Game> populateDummyGames(){ 
    List<Game> games = new ArrayList<Game>(); 
    games.add(new Game(counter.incrementAndGet(), "The Elder Scrolls V: Skyrim", "RPG", "Bethesda Game Studios", "Bethesda")); 
    games.add(new Game(counter.incrementAndGet(), "Halo: Combat Evolved", "First-Person-Shooter", "Bungie", "Microsoft")); 
    games.add(new Game(counter.incrementAndGet(), "Doom", "First-Person-Shooter", "ID-Studios", "Bethesda")); 

    return games; 
    } 
} 

后,我开始春季启动应用程序,并通过卷曲发送请求到本地主机:8080,没有链接到我的API。

编辑 我忘了包括我的pom.xml文件。也许这事做的问题:

<modelVersion>4.0.0</modelVersion> 

<groupId>com.example</groupId> 
<artifactId>demo</artifactId> 
<version>0.0.1-SNAPSHOT</version> 

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.5.7.RELEASE</version> 
</parent> 

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-data-rest</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-data-jpa</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>com.h2database</groupId> 
     <artifactId>h2</artifactId> 
    </dependency> 
</dependencies> 
<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 
</project> 

编辑:
我想它了...我觉得有点愚蠢。 在RestApiController.java,对于第一种方法的RequestMapping设置为

/game/ 

这是没有意义的我。所以我只尝试通过localhost访问它:8080/api/game。当通过本地主机访问:8080/api /游戏/时,它工作正常..对不起..但感谢您的帮助!

+2

你知道@ @ RequestMapping吗?运行您的应用程序并尝试使用http:// localhost:8080/api/game/ –

+0

如果应用程序未在根上下文中启动,则可能需要使用上下文路径。 –

+0

当你打本地主机时出现什么错误:8080/api/game,并且检查你的服务器日志中的映射日志,检查映射的url与调度程序servlet,并且每个请求映射端点 –

回答

0

好吧,我相信问题是:

@SpringBootApplication(scanBasePackages= {"demo"}) 

尝试将其更改为

@SpringBootApplication(scanBasePackages= {"demo.app"}) 

@SpringBootApplication 
@EnableAutoConfiguration 

随着@EnableAutoConfiguration弹簧会自动配置豆你”我需要。

+4

“@ SpringBootApplication”注释等同于使用@ Configuration,@ EnableAutoConfiguration和@ ComponentScan'及其默认属性。 –

+0

哦!不知道,谢谢! –

+0

如果您的控制器不在您定义了SpringBootApplication的相同/子包中,则需要放置scanBasePackages。在这种情况下,SpringBoot在demo.app中定义,控制器在demo.app.controller中,所以你不需要放置scanBasePackages –