I am trying to connect my e-commerce project backend to swagger2. I have installed all the dependencies, yet I still cannot do it.
This is the dependency declared in my pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
This is one of my user controller files:
@RestController
@RequestMapping("/api")
@CrossOrigin
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/")
public List<User> GetUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User GetUser(@PathVariable String id) {
return userRepository.findById(id).orElse(null);
}
@PostMapping("/")
public User postMethodName(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/")
public User PutMapping(@RequestBody User newUser) {
User oldUser = userRepository.findById(newUser.getId()).orElse(null);
oldUser.setName(newUser.getName());
oldUser.setEmail(newUser.getEmail());
oldUser.setPassword(newUser.getPassword());
userRepository.save(oldUser);
return oldUser;
}
@DeleteMapping("/{id}")
public String DeleteUser(@PathVariable String id) {
userRepository.deleteById(id);
return id;
}
}
This is the code of my main application:
package com.omazon.ecommerce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class ECommerceApplication {
public static void main(String[] args) {
SpringApplication.run(ECommerceApplication.class, args);
}
}
Lastly, this is what I declared in the application.properties
file:
spring.data.mongodb.uri=mongodb://localhost:27017/e-commerce
This is the picture of the error I got:
Swagger2's usage seems to require (or at least often includes) the concept of a Docket
api via an instantiation such as new Docket()
or new Docket(DocumentationType.SWAGGER_2)
. I don't see that in your code snippets, so wonder if that may be one issue.
Per the swagger docs, Docket
is Springfox’s primary api configuration mechanism.
Specifically, this section regarding configuration may be helpful. Note the Docket
instantiation:
...
@Bean //Don't forget the @Bean annotation
public Docket customImplementation(){
return new Docket()
.apiInfo(apiInfo());
//... more options available
...
There's also a more complete example in those same docs here.
For reference, there's another usage example in this tutorial.