spring boot sample code
by 개발자   2024-02-08 09:10:29   조회수:492

Spring Boot offers a variety of sample projects depending on your specific needs and desired functionality. Here are a few options to get you started:

Basic Spring Boot Application:

This is the most fundamental example, demonstrating the core principles of Spring Boot. It simply returns a "Hello, World!" message when accessed.

Java
@SpringBootApplication
public class MySpringBootApp {

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

    @GetMapping("/")
    public String hello() {
        return "Hello, World!";
    }
}

Spring Boot with REST API:

This example showcases creating a basic REST API endpoint that returns a JSON response.

Java
@SpringBootApplication
@RestController
public class MyRestController {

    @GetMapping("/api/message")
    public String getMessage() {
        return "Hello from Spring Boot API!";
    }
}

Spring Boot with Database Access:

This example demonstrates connecting to a database and fetching data using JPA repositories.

Java
@SpringBootApplication
@EnableJpaRepositories
public class MyDataApp {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userRepository.findAll();
    }
}

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    // Getters and setters
}

Further Resources:

Remember to adjust these examples based on your specific project requirements and dependencies.

Feel free to ask if you have any further questions or need help with a specific use case!