Tuesday, 26 March 2024

Run springboot jar as service in Linux (or) Azure VM


 Create as .sh file add jar execution command

/usr/bin/java -jar /u01/api/docuchat-api-0.0.1.jar --spring.config.location=file:/u01/api/config/ > /u01/api/logs/springboot.log


in you case you can use only /usr/bin/java -jar jarname.jar 

Create .service file under /etc/systemd/system/ folder

my file name: dora-api-demo.service
Script is below 

[Unit]
Description=dora-demo-api

[Service]
User=root
WorkingDirectory=/usr/local/bin
ExecStart=/usr/bin/bash /u01/api/dora-service.sh
SuccessExitStatus=0

[Install]
WantedBy=multi-user.target

once the script is passed inside the dora-api-demo.service file
need use below command to 
sudo systemctl daemon-reload
sudo systemctl enable dora-api-demo
sudo systemctl start dora-api-demo  (To start the service)
sudo systemctl status dora-api-demo (To check the status of the service)
sudo systemctl stop dora-api-demo (to stop the service)
sudo systemctl restart dora-api-demo (to restart the service)


Thursday, 21 March 2024

Records in java, canonical constructor & compact constructor using java

 Record is a certain type of  class. It is also special type of class.

We can create recording like below

public record EmployeeRecord(String name, int employeeNumber) {

}


We can access the name, employeeNumber, as below

For Example: EmployeeRecord record = new EmployeeRecord("Dinesh", 24);

record.name();

record.employeeNumber();


- if you declare record instance variables are final by default. 

- toString(), hashCode() & equal() are overrided automatically.

- We can't extend any class or record 

- we can implement the interface at end before flower braces

- By default the records is final. we don't required to declare final variable.

- By default Canonical Constructor is created. 

 - We can declare the variable with static final 

- we can declare the static methods 

Canonical Constructor is a constructor that is created with all instance fields as a parameters 

for example from above code 

    public EmployeeRecord (String name, int employeeNumber ) {

        this.name = name;

        this.employeeNumber = employeeNumber;

    }

- if you want override constructor you can do. Why do we required to override constructor is if need to do some validation like age should not be negative then you can throw exception if required.

- We can use Compact Constructor instead of overriding it.

What is the Compact Constructor?

  Compact Constructor with our argument or bracket we can declare need to declare as below

public EmployeeRecord {

     if (employeeNumber < 0) {

        throw new ILegalArgumentException("Not valid number");

    }

}