Spring Boot Knowledgebase (Part 1)

  • Auto-configure the application dependency to compile and run based on the artifacts, which are found on the classpath of the application.
  • Provide lots of non-functional features in a production environment, such as security or health checks
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
import org.springframework.boot.SpringApplication;@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(StarterApplication.class, args);
}
}
spring-boot: run (run the spring boot application)
spring-boot: repackage
(repackage the application as jar or war
format)
spring-boot: start |
spring-boot: stop |
those two manage the lifecycle of the spring bootapplication and helping the test the application using integration testing
spring-boot: build-info (generate the build information which will help the actuator process the application status)

What Embedded Servers?

Step 1: Install Java
Step 2: Install Web Server(Tomcat/Websphere/WebLogic)
Step 3: Deploy the application war file to Web server

How to Deploy Spring Boot Web Applications as Jar and War Files?

  1. Add the plugin to pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<packaging>jar</packaging>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId
<scope>provided</scope>
</dependency>
<packaging>war</packaging>

How To access the properties value in Spring boot at Class and Models and controller?

@Value annotation is used to get external access to the properties
  1. Using Application Properties (application.properties)
  2. Command-line properties (Convert the argument to properties and add them to set environment properties)
  3. Profile-specific properties — these properties are loaded from the application-{profile}.properties or its YML file
  1. Endpoint: endpoint allows the developer to monitor and interact with the application. for example, the /health endpoint provides the basic health information of the application. /actuator/health
  2. Metrics: it provides dimensional metrics by integrating the micrometer. it provides the timers, gauges, counter, distribution summary and long task timer with dimensional data
  3. Audit: Spring provides a flexible audit framework that publishes events to an audit event repository.
Java 8+
Spring framework 5.1.9+
<!-- MySQL JDBC driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.19'
  1. Declare the properties in applications.properties
spring.datasource.url =jdbc:mysql://localhost:3306/testapp?useSSL=false
spring.datasource.username
=root
spring.datasource.password
=ronnie
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto
= update
logging.level.org.hibernate.SQL= DEBUG
logging.level.org.hibernate.type
=TRACE
import org.springframework.jdbc.core.JdbcTemplate;public class EmployeeDao {private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public int saveEmployee(Employee e){
String query="insert into employee values( '"+e.getId()+"',
'"+e.getName()+"',
'"+e.getSalary()+"')";
return jdbcTemplate.update(query);
}
}
server.http2.enable = true
1. Download Spring CLI, extract the folder
2. Set the Path to environment by `bin` folder
3. Check the version in terminal by “spring -version”
@RestController
class HelloWorld {
@RequestMapping(“/“)
String hello() {
“Hello world”
}
}
spring run <Spring_Groovy-ScriptName>
@EnableAutoConfiguration(exclude={dataSourceAutoConfiguration.class})
@EnableAutoConfiguration(excludeName={Sample.class})
spring.autoconfigure.exclude= class1, class2, class3
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.1</version>
</dependency>
//https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-dependency-plugin
compile group: 'org.apache.maven.plugins', name: 'maven-dependency-plugin', version: '3.1.1'
@Component
@ConfigurationProperties(“example”)
public class SampleConfiguration {
private int number;
private boolean value;
private String message;
}
example.number = 100
example.value= true
example.message= Dynamic Message
  1. YamlMapFactoryBean to load YAML as a MAP
  2. YamlMapPropertiesFactoryBean to load YAML as Properties
  1. Expose the Rest server around spring data, without write a lot of code
  2. support SQL and Non_SQL based databases
  3. Support Pagination
  4. Enable filtering
  5. Allow sorting
  6. Support HATEOAS
  1. Create the @Entity for application
  2. Then use @RepositoryRestResource
@RepositoryRestResource(collectionResourceRel= “todos”, path=“todos”)
public interface TotoRepository extend PaginationAndSortingRepository<Todo, Long> {
List<Todo> findByUser(@Param(“user”) string user)
}
  1. first, need to mention the fully-qualified name the @EnableAutoConfiguratin key META-INF/spring factories file
  2. if will build with maven then the file should be placed in the resources/META-INF directory
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@RestController
class HelloController {
private static final Logger logger = LogManager.getLogger(HelloController.class);@GetMapping(“/“)
public String main(@PathVariable sting name) {
logger.debug(“My name is {}“, name)
return name;
}
}
  1. Create the folder and name it as static number resource folder
  2. In this folder, you can put the static content,
value : store the type of beans to be checked
name: name of the beans to be checked
  1. application.properties for production
  2. application-dev.properties for dev
  3. application-test.properties for test
spring.profile.active = prod
spring-boot:run -Dspring.profiles.active=prod
  • sampleProp
  • sample-Prop
  • sample_Prop
  • SAMPLE_PROP
import javax.persistence.Entity
import javax.persistence.Table
@Entity
@Table(name=“employees”)
public class Employee {
}
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
@Servicepublic class EmployeeService {@Autowired
EmployeeRepository repository;
public List<Employee> getAllEmployees() {List<Employee> employeeList = repository.findAll();if (emplouyeeList.size() >0){
return employeeList;
} else {
return new ArrayList<Employee>();
}
}
}
@RestController
@RestMapping(“/employee”)

public class EmployeeController {

@Autowired
EmployeeService employeeService;

@GetMapping
public ResponseEntity<List<Employee>> getAllEmployee() {

List<Employee> list = service.getAllEmployees();
return new ReponseEntity<List<Employee>>(list,
new HttpHeader(), HttpStatus.OK);
}
}
# Enabling HTTP response compression in spring boot
server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

--

--

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