NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If the Java Main class and Controllers are in different packages, then we need to explicitly mention the Controller package/class using @ComponentScan(basePackageClasses = DemoController.class):
@SpringBootApplication
@ComponentScan(basePackageClasses = DemoController.class)
public class SpringBootMain {
//code here
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Complete Example: https://dzone.com/articles/why-springboot
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Spring Boot includes a Maven plugin that can package the project as an executable jar. Add the plugin to your <plugins> section if you want to use it:

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The spring-boot-starter-parent chooses fairly conservative Java compatibility. If you want to follow our recommendation and use a later Java version you can add a java.version property:

<properties>
<java.version>1.8</java.version>
</properties>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Spring Boot dependencies use the org.springframework.boot groupId. Typically your Maven POM file will inherit from the spring-boot-starter-parent project and declare dependencies to one or more “Starters”.
Spring Boot also provides an optional Maven plugin to create executable jars.
Here is a typical pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
+instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>

<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
To configure your project to inherit from the spring-boot-starter-parent simply set the parent:

<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
You can specify multiple profile-specific YAML documents in a single file by using a spring.profiles key to indicate when the document applies. For example:

server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production
server:
address: 192.168.1.120
In the example above, the server.address property will be 127.0.0.1 if the development profile is active.
If the development and production profiles are not enabled, then the value for the property will be 192.168.1.100.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DataSource configuration is controlled by external configuration properties in spring.datasource.*.
For example, you might declare the following section in application.properties:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
For instance, if you are using the Tomcat connection pool you could customize many additional settings:

# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=50

# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
JavaConfig-Based Configuration:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.sivalabs.demo")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig
{
@Bean
public UserService userService(UserDao dao){
return new UserService(dao);
}
@Bean
public UserDao userDao(DataSource dataSource){
return new JdbcUserDao(dataSource);
}
@Bean
public DataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("secret");
return dataSource;
}
}

Marked it as a Spring Configuration class using @Configuration annotation.
Enabled Annotation based transaction management using @EnableTransactionManagement
Configured @EnableJpaRepositories to indicate where to look for Spring Data JPA repositories
Configured PropertyPlaceHolder bean using @PropertySource annotation and PropertySourcesPlaceholderConfigurer bean definition, which loads properties from application.properties file.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Embedded Web Server Deployment:

Out of the box, Spring Boot uses a public static void main entry-point that launches an embedded web server for you.

If you use the Maven build (mvn clean install) provided by the Spring Boot Initialzr, you’ll get a fat jar.
This jar is handy because it includes all the other dependencies and things like your web server inside the archive.
You can give anybody this one .jar and they can run your entire Spring application with no fuss: no build tool required, no setup, no web server configuration, etc: just java -jar ...your.jar.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Tomcat:

When you run your application, Spring Boot will detect that you have a Spring MVC controller and start up an embedded Apache Tomcat 7 instance, by default.
You should be able to test the REST endpoint by opening up your browser and hitting http://localhost:8080/hello/World.

By default, Spring Boot uses Tomcat 7. If you want to use Tomcat 8, just say so! You need only override the Maven build’s tomcat.version property and this will trigger the resolution of later builds of Apache Tomcat.

<properties>
<tomcat.version>8.0.3</tomcat.version>
</properties>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Jetty:

Of course, some of you may want to use the Jetty embedded servlet container. Jetty’s a fine choice, as well.
You can simply exclude the Spring Boot starter Tomcat module and then import the Spring Boot Starter Jetty module.
Spring Boot will automatically delegate to that, instead. Here’s the revised dependencies section of our Maven build:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
If you want to switch to Jetty 9, that’s easy as well. Ensure you have the following properties in your Maven build.

<properties>
<java.version>1.7</java.version>
<jetty.version>9.1.0.v20131115</jetty.version>
<servlet-api.version>3.1.0</servlet-api.version>
</properties>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SpringBoot SpringData JPA:
https://www.javacodegeeks.com/2018/03/spring-data-jpa-example-with-spring-boot.html


PersonRepository.java


import com.javacodegeeks.jpaexample.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}
Although above interface definition is empty, we still have some points which we need to understand:

@Repository annotation marks this interface as a Spring Bean which is initialised on application startup. With this annotation, Spring takes care of managing exception database interaction throws gracefuly
We used Person as a parameter to signify that this JPA interface will manage the Person Entity
Finally, we also passed the data type Long as a parameter. This signifies that the Person Entity contains a unique identifier which is of the type Long.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Q : Why do we need spring-boot-maven-plugin?
spring-boot-maven-plugin provides a few commands which enable you to package the code as a jar or run the application

spring-boot:run runs your Spring Boot application.
spring-boot:repackage repackages your jar/war to be executable.
spring-boot:start and spring-boot:stop to manage the lifecycle of your Spring Boot application (i.e. for integration tests).
spring-boot:build-info generates build information that can be used by the Actuator.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Spring Annotations:
1- @SpringBootApplication(scanBasePackages="com.scb")
2- @Configuration
3- @ImportResource({"classpath:/camel/camel-filemanagement-routes.xml"})
4- @Repository
5- @Autowired
6- @JsonProperty("payloadRequest")
7- @Param("entityType") String entityName --
8- @XmlElement(name = "Prty")
9- @XmlSchemaType(name = "string")
10- @Override
11- @Scope(value="prototype")
12- @POST, @DELETE, @PUT, @GET (JAX-RS)
13- @Produces(MediaType.APPLICATION_JSON) (JAX-RS)
14- @Consumes(MediaType.APPLICATION_JSON) (JAX-RS)
15- @Path("/postAceEvent") (JAX-RS)
16- @RequestMapping
17- @RequestURL ---
18- @PathParam (JAX-RS) ( equivalent to @PathVariable)
19- @QueryParam (JAX-RS) (equivalent to @RequestParam)
20- @RequestParam
21- @Qualifier
22- @Controller
23- @Service
24- @RestController (@Controller and @ResponseBody)
25- @Component
26- @EnableAutoConfiguration
27- @ComponentScan(basePackages = { "com.baeldung.web.controller" })
28- @RequestBody (Converts response object to HttpResponse)
29- @ResponseBody (Converts HttpRequest to Object)
30- @GetMapping ( equivalent to @RequestMapping(method = RequestMethod.GET))
31- @PostMapping (equivalent to @RequestMapping(method = RequestMethod.POST))
32- @PutMapping (equivalent to @RequestMapping(method = RequestMethod.PUT))
33- @PatchMapping (equivalent to @RequestMapping(method = RequestMethod.PATCH))
34- @DeleteMapping (equivalent to @RequestMapping(method = RequestMethod.DELETE))
35- @ExceptionHandler




Spring Annotation JAX-RS Annotation
@RequestMapping(path = "/troopers" @Path("/troopers")
@RequestMapping(method = RequestMethod.POST) @POST
@RequestMapping(method = RequestMethod.GET) @GET
@RequestMapping(method = RequestMethod.DELETE) @DELETE
@ResponseBody N/A
@RequestBody N/A
@PathVariable("id") @PathParam("id")
@RequestParam("xyz") @QueryParam('xyz")
@RequestMapping(produces = {"application/json"}) @Produces("application/json")
@RequestMapping(consumes = {"application/json"}) @Consumes("application/json")




@Autowired vs @Inject(JSR : Java Specification Request)
@Resource







@RequestMapping(path = "/{id}", method = RequestMethod.GET)
public Stormtrooper getTrooper(@PathVariable("id") String id) throws NotFoundException {
}


@RequestMapping(path = "/{id}", method = RequestMethod.POST)
public Stormtrooper updateTrooper(@PathVariable("id") String id, @RequestBody Stormtrooper updatedTrooper) throws NotFoundException {
return trooperDao.updateStormtrooper(id, updatedTrooper);
}





Hibernate vs JPA vs MyBatis
Comparator vs Comparable
equals() vs toString()
OutOfMemoryError , MemoryLeak, StackOverFlowError (Browser Bookmark)





---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

@Configuration
@EnableScheduling
public class ScheduledConfiguration {

@Scheduled(fixedRate = 5000)
public void executeTask1() {
System.out.println(Thread.currentThread().getName()+" The Task1 executed at "+ new Date());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Scheduled(fixedRate = 1000)
public void executeTask2() {
System.out.println(Thread.currentThread().getName()+" The Task2 executed at "+ new Date());
}
}

-------------------------------------------------------------------------------------------------------------------------------------------------
@EnableConfigServer: Add the EnableConfigServer annotation before the class and build the project once again. With this annotation, this artifact will act like a spring config server. (https://howtodoinjava.com/spring-cloud/spring-cloud-config-server-git/)

@RefreshScope:
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.