✍️
Notes.md
  • Table of contents
  • React.Js
    • React Hooks
    • Old :- React : Using Classes
  • Blockchain
    • Solidity
    • Custom ERC20 token
    • Contract
  • Tools and Tech
    • Docker
    • Git version Control
  • Java
    • Data & Data Types
    • IO in Java
    • Data Structures
      • Array in Java
      • Collections in Java
      • Map in Java
      • Enums in Java
      • Linked List in Java
      • List in Java
      • Queues & Stacks
      • Set in Java
      • TreeSet and TreeMap
    • Object Oriented Programming
      • Object Class Methods and Constructor
      • Immutable Class & Objects
      • Constructors
      • Visibility
      • Generics
    • Threads in Java
    • Useful Stuff Java
      • Lambda & Stream
    • Keywords in Java
      • Annotations
      • Comparators
      • Packages in Java
    • Miscellaneous
    • Articles to refer to
  • Golang
    • Competitive Programming in Go
    • Testing simple web server
    • Learning Go : Part 1
    • Maps vs slices
    • Golang Garbage Collector 101
    • Things Golang do differently
    • Go Things
  • Linux
    • Shell programming
    • Linux Commands Part 1 - 4
    • Linux Commands Part 5 - 8
    • Linux Commands Part 9 - 10
  • Software Design
    • Solid Design
    • OOPS
    • Design Patterns
      • Creational Design Pattern
        • Builder DP
        • Factory DP
        • Singleton DP
      • Adapter DP
      • Bridge DP
      • Iterator DP
      • State DP
      • Strategy DP
      • Behavioral Design Pattern
        • Observer DP
      • Structural Design Pattern
        • Facade DP
  • Cloud
    • Google Cloud Platform
      • GCP Core Infrastructure
      • Cloud Networking
  • Spring Boot
    • Spring Basics
      • Spring Beans
      • Important Annotations
      • Important Spring Things
      • Maven Things
      • Spring A.O.P
    • Spring Boot Controller
      • Response Entity Exception Handling
    • Spring Things
    • Spring MVC
    • Spring Data
      • Redis
      • Spring Data JPA
      • JDBC
    • Apache Camel
  • Miscellaneous
    • Troubleshooting and Debugging
Powered by GitBook
On this page
  • Spring Scheduling
  • Spring Validation
  • To handle error
  • Defining on controller
  • Faker

Was this helpful?

  1. Spring Boot

Spring Things

Spring Scheduling

// enable using 
@EnableScheduling
// on Main class

@Slf4j
@EnableAsync
public class SampleScheduler {

    @Async
    @Scheduled( cron = "* * * * * *" )
    // initialDelay = 1000
    // fixedDelay = 1000
    // fixedRateString = "PT02S"
    // cron stars : seconds, minutes, hours, day of month, month, day of week
    public void scheduler() throws InterruptedException {
        LocalDateTime current = LocalDateTime.now();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
        String formattedDateTime = current.format(format);
        log.info("Scheduler time : " + formattedDateTime);

        // this will cause log print to delay 1 more second, new time 2 seconds
        Thread.sleep(1000);
    }

Spring Validation

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {

    private final UUID id;

    @NotBlank
    @NotNull(message = "username should not be null")
    private final String name;

    @Email
    private String email;

    @Min(0)
    @Max(100)
    private int age;

    public Person(@JsonProperty("id") UUID id,
                  @JsonProperty("name") String name) {
        this.id = id;
        this.name = name;
    }

    public UUID getId() {
        return id;
    }

    public String getName() {
        return this.name;
    }
}

To handle error

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException exception) {
    Map<String, String> errorMap = new HashMap<>();
    for (FieldError fieldErrors : exception.getBindingResult().getFieldErrors()) {
        errorMap.put(fieldErrors.getField(), fieldErrors.getDefaultMessage());
    }

    return errorMap;
}

Defining on controller

@PostMapping
public int addPerson( @Valid @NonNull @RequestBody Person person) {
    return personService.addPerson(person);
}

Faker

To generate fake data

<dependency>
        <groupId>com.github.javafaker</groupId>
        <artifactId>javafaker</artifactId>
        <version>1.0.2</version>
</dependency>



@Bean
public Faker faker() {
	return new Faker();
}

private final Faker faker;

@Override
public void run(String... args) throws Exception {

// create 100 rows of people in the database
List<Person> people = IntStream.rangeClosed(1, 100)
        .mapToObj(i -> new Person(
                faker.name().firstName(),
                faker.name().lastName(),
                faker.phoneNumber().cellPhone(),
                faker.internet().emailAddress(),
                new Address(
                        faker.address().streetAddress(),
                        faker.address().city()
                )
        )).toList();

repository.saveAll(people);
}

PreviousResponse Entity Exception HandlingNextSpring MVC

Last updated 2 years ago

Was this helpful?