Moving From the Full-stack JS World to the Java Galaxy ⚡⚡

My Beginning 🚲 :

My Beginning

My Steps With Java (Spring boot framework)

Spring Boot

Learning RoadMap 🚗:

Things learned until Now :

Spring boot Annotations ✂️ 📐:

@RestController : To make simply a Rest Controller in spring (specialized version of @Controller in Spruing MVC)@RequestMapping("/users"): to map the HTTP Requests to the concerned controller (for our example to handle all the api requests to /users
@GetMapping("/all") : to map only the HTTP GET requests@PostMapping : to map only the HTTP POSTrequests@RequestMapping(value = "/yourUrl", method = RequestMethod.POST):Another method to define your HTTP requests handler , you can specify the method POST | GET | PUT | DELETE etc..@PathVariable : used to pass params via URI , example /users/{userId}@RequestBody: maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization@RequestParam(value = "paramName", required = false): to inject params with your HTTP requests for example GET API with filter
yourUrlAPi?paramName=__value__
@ControllerAdvice: allows to handle exceptions across the whole application in one global handling component
@Service : annotation is used with classes that provide some business functionalities
@Repository :  is a Spring annotation that indicates that the decorated class is a repository
Class : HandlerInterceptor : 
* preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
* postHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
* afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler) :
Example class to add an interceptor to your spring boot application to catch the requets and it's provide methods to follow teh requets lifecycle
@Value("${spring.application.urlApi}") : annotation is used to assign default values to variables and method arguments, fro example from your application.properties to your classes attributes

@Document : to define your class as a document to be stored in your Mongodb Database (thanks to Spring data )
@Id :applied at the field level to mark the field used for identiy purpose.@NotBlank(groups = ModelCreation.class,message = "fieldName.notSetted")@NotNull(groups = ModelCreation.class,message = "fieldName.notSetted") :
Are used for to some some constraints validations
@DBREF : Annotation used to define the concerned fiedl as reference to another document
public interface EntityNameMapper extends EntityMapper<ModelDTO, Model>
public abstract class AbstractAuditingEntity implements Serializable {

private static final long serialVersionUID = 1L;

@CreatedBy
private User createdBy;

@CreatedDate
private Instant createdDate = Instant.now();


@LastModifiedBy
private User lastModifiedBy;


@LastModifiedDate
private Instant lastModifiedDate = Instant.now();

The Design Patterns ⚒ 🛠 ⛏:

public class yourClass{

private String field;



public String getField() {
return field;
}

public yourCla field(String field) {
this.field= field;
return this;
}

Recommended Project structure 📓 📕 📗 📘 📙 📔 :

JAVA 8 Features practiced ✏️ :

String[] str = new String[10];     
Optional<String> isNull = Optional.ofNullable(str[9]);
if(isNull.isPresent()){
//Getting the substring
String str2 = str[9].substring(2, 5);
//Displaying substring
System.out.print("Substring is: "+ str2);
}
else{
System.out.println("Cannot get the substring from an empty string");
}
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

Cools things are done with Spring Boot ✌️ :

Scheduled Tasks :

@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
logger.info("Java cron job expression:: {}" ,strDate);
}

Custom Annotations :

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = ValueOfEnumValidator.class)
public @interface ValueOfEnum {
Class<? extends Enum<?>> enumClass();

String message() default "must be any of enum {enumClass}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}
-------------------------------------------------------------------------------------------------------------------------------
"Second Use Case"
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface EventCaptor {

ActionType actionType();
}
@PostMapping
@EventCaptor(actionType = ActionType.CREATION)
@ApiOperation(value = "Create a new instance")
public ResponseEntity<ProductDTO> createProduct( @RequestBody @Valid ProductDTO classDTO, Principal principal)
throws URISyntaxException {
final classDTO result = classService.createExample(classDTO);
return ResponseEntity.created(new URI("/api/class/")
}

Aspect-oriented programming :

@Aspect
@Component
public class YourClassAspect {
@AfterReturning(value = "execution(* com.softilys.soyouz.web.rest..*(..))", returning = "retVal")
public void auditEventPointcut(JoinPoint pjp, ResponseEntity retVal) {
EventCaptor myAnnotation =
((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(EventCaptor.class);
String[] argNames = ((MethodSignature) pjp.getSignature()).getParameterNames();
String productId = "";
if (myAnnotation != null
&& checkReturnedValueIsNotEmptyResponseEntity(retVal)
&& (myAnnotation.actionType().equals(ActionType.CREATION)
|| myAnnotation.actionType().equals(ActionType.UPDATE))) {
//---------your action------------//
}
}

Custom Mongodb Queries:

final Query query = new Query();
query.addCriteria(Criteria.where("criteriaOne").is(productID));
query.with(Sort.by(Sort.Direction.ASC, "createdDate"));
return mongoOperations.find(query, YourClas.class);

Code Refactoring ⛏ :

Conclusion ✍️:

Unlisted

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rebai Ahmed

Rebai Ahmed

<script>alert('try your best')</script>