# JAVA SPRING (commpany) ###### tags: `Springs` `company` IDE: eclipse 版本號 ``` <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> ``` 更改 pom.xml (執行前,要先更新meaven ) ``` <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> ``` 建立mvc架構 1. controller * 一定要建立@Restcontroller * @RequestMapping 啟動web mvc * @GetMapping、@PostMapping 分別為GET、Post,後面接自訂api * @PostConstruct 注入符合model資料 ``` @RestController @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE ) public class ProductController { @PostConstruct private void initDB() { } @GetMapping("/products/{id}") return ResponseEntity.ok().body(product); } @PostMapping("/products") public ResponseEntity<Product> createProduct(@RequestBody Product request) { boolean isIdDuplicated = productDB.stream() .anyMatch(p -> p.getId().equals(request.getId())); if (isIdDuplicated) { return ResponseEntity.status(HttpStatus.CONFLICT).build(); } return ResponseEntity.created(location).body(product); } } ``` 2. model ``` public class Product { private String id; private String name; private int price; ``` 快速建立model  <font color="red">結果如下 </font> ``` public Product() { } public Product(String id, String name, int price) { this.id = id; this.name = name; this.price = price; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up