Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Aphorismen
Applications
Business Economics & Admin.
My Computers
Cooking
Devices
Folders
Food
Hardware
Infos
Software Development
Sports
Operation Instructions
Todos
Test
Help
Glossary
Community portal
adaptions
Sidebar anpassen
Wiki RB4
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
SpringBoot
Page
Discussion
English
Read
Edit
View history
Toolbox
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Introduction== * Framework to build microservices * common non-functional features * not zero code generation * not a web or application server * provides starter projects * embedded server (incl. in application jar) * externalized configuration ==Installation== * see [[EDTLaptop1#Spring_Boot_CLI|Window Laptop Spring Boot CLI]] ==Concepts== * SpringBoot Autoconfiguration: by scanning the classpath * Dispatcher Servlet * SpringBoot Actuator (for monitoring) ===Architecture=== * Client -> Controller -> Service (Business Logic) -> Model ===[[Rest|Rest]]=== * see [https://spring.io/guides/tutorials/rest/ here] ===Application Context=== The '''ApplicationContext''' is where Spring holds instances of objects that it has identified to be managed and distributed automatically. These are called [[#Beans|Beans]]. The application context can also be autowired: @Autowired private ApplicationContext applicationContext; ===Dependency Injection=== ===Beans=== * Beans are specified by class level annotations e.g. <code>@Component, @Service, @Repository</code> etc. or by XML configuration. The annotations are hierachical meaning for example that there are more specialized annotations for <code>@Component</code>. *<code>@Bean</code> is a special annotation on method level. * A java class becomes Spring Bean only when it is created by Spring * On startup/runtime classes in the application will be scanned and each class annotated with spring annotations will be instantiated as beans and put into a global context (Spring applicationcontext). * Entities are no beans * You can autowire only those beans whose life-cycle are managed by Spring IoC container. * Spring support @Autowire only for Spring Beans * the default scope is singleton ===Security=== adding to <code>pom.xml</code>: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>'''spring-boot-starter-security'''</artifactId> </dependency> and update the project automatically sets up '''form-based authentication''' with a generated session cookie generated on the server or '''basic authentication''' with a header sent along with every request * user='user * pwd=see console output of server start or set it in <code>[[#Application_Properties|application.properties]]</code> spring.security.user.name=uwe spring.security.user.password=uwe This has to be entered just once. ===Testing=== <dependency> <groupId>org.springframework.boot</groupId> <artifactId>'''spring-boot-starter-test'''</artifactId> <scope>test</scope> </dependency> This integrates the frameworks JUnit, Hamcrest, Mockito, When you build a Spring boot application using Spring Initializer. It auto creates a <code>@SpringBootTest</code> annotated class for you with <code>contextLoads()</code> empty method. <code>@SpringBootTest</code> by default starts searching in the current package of the test class and then searches upwards through the package structure, looking for a class annotated with <code>@SpringBootConfiguration</code> from which it then reads the configuration to create an application context. ====TestRestTemplate==== * TestRestTemplate is part of the Spring Boot Test module and provides a high-level, programmatic way to test RESTful services by making actual HTTP requests to the service. It allows you to send HTTP requests (GET, POST, PUT, DELETE, etc.) to your application's REST endpoints and receive actual HTTP responses. * It starts an embedded server (typically an embedded Tomcat or Jetty instance) and sends requests to the server as if they were real HTTP requests. * TestRestTemplate is more suitable for integration testing and end-to-end testing because it interacts with the running server, making actual network calls. ====MockMvc==== * MockMvc, on the other hand, is a part of the Spring Test framework and is specifically designed for testing the controllers of your Spring application in isolation. * It allows you to perform requests against your controller methods without starting a full server. * With MockMvc, you can simulate HTTP requests and responses without making actual network calls. This makes it a more suitable choice for unit testing and integration testing of your Spring MVC controllers. * MockMvc provides a fluent and expressive API for setting up requests, sending them to your controllers, and then validating the results. ==Configuration== Spring Boot allows you to '''externalize''' your configuration. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration which are evaluated in a specific order (see [https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html here]). ===Application Properties=== It is located in <code>\<Project>\src\main\resources\application.properties</code>. In addition to this file profile specific propertiers can be set by the naming convention <code>application-{profile}.properties</code> at the same location. Placeholders can be used to get the value from the environment or properties defined before with <code>x.y.z=${ENV}</code>. logging.level.org.springframework = debug # Profile setting spring.profiles.active=dev // hard coded spring.profiles.active=@spring.profiles.active@ // the Spring Boot Resources Plugin replaces it during the [[Maven#Profiles|Maven]] build // with the active profile from pom.xml in the <code>\target\classes\</code> directory. # security configuration see [[#Security|here]] # MySQL configuration see [[SpringBoot#MySQL|here]] # H2 database configuration see [[#H2_Database_Configuration|here]] # logging configuration see [[#Logging|here]] # actuator see [[#Actuator|here]] ===Logging=== Spring Boot is using LogBack as a logging proivder by default. It is not totally clear which configuration has which impact (application.properties, log-back-spring.xml). A good description is [https://howtodoinjava.com/spring-boot2/logging/spring-boot-logging-configurations/ here]. The default log output is <DATE> <TIME> <LOG_LEVEL> <PROCESS_ID> --- <THREAD_NAME> [<LOGGER_NAME>] <LOG_MESSAGE> To implement logging import org.slf4j.Logger; import org.slf4j.LoggerFactory; final static Logger logger = LoggerFactory.getLogger(BookmarksRestController.class); // is the LOGGER_NAME BookmarksRestController.logger.trace(... The general configuration in [[#Application_Properties|application.properties]]: # a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information debug=true # enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio) trace=true logging.file.name=./log/bookmarks.log logging.logback.rollingpolicy.max-history=5 # double backslash quote for policy and logback logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{1}.%M{}\\(\\) - %L: %m%n logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{1}.%M{}\\(\\) - %L: %m%n The specific configuration can be set according to package/class hierachy: logging.level.<PACKAGE_NAMEn>=<LEVEL> logging.level.<PACKAGE_NAME1.PACKAGE_NAME2>=<LEVEL> logging.level.<PACKAGE_NAME1.PACKAGE_NAME2.CLASSNAME>=<LEVEL> // e.g. logging.level.com.uweheuer=INFO logging.level.com.uweheuer.bookmarks=TRACE logging.level.com.uweheuer.bookmarks.entities=INFO ====LogBack==== * good description [https://www.codingame.com/playgrounds/4497/configuring-logback-with-spring-boot here] * <code>/src/main/resource/log-back-spring.xml</code> ===Actuator=== * standard monitoring, status information, ... * add dependency to pom.xml * configure the available endpoints in application.properties management.endpoints.web.exposure.include=env,health,info * example implementation in [[Heroku#Spring_Boot_Demo|Heroku Demo Project]] ==Implementation== The standard implementation is heavily using a starter configuration provided by maven plugins. ===Folder Structure=== \target\ // contains the jar file of the Spring Boot application ===Package Structure=== There are two main approaches: structure by layer or structure by feature. It seems that a structure by feature is the most commonly used. ===Static Content=== * <code>\src\main\resources\static\</code> will be used in Spring Boot application by copying to <code>\target\classes\static\</code> * sources which have to be transpiled like Angular apps should not be located here but in a separate directory <code>\src\main\resources\<APP>\</code> * for Angular: ** adjust angular.json with "outputPath": "../../main/resources/static/", ===Main Application=== see <code>/test1/src/main/java/com/uweheuer/springboot/test1/Test1Application.java/</code> @SpringBootApplication public class Test1Application { ... public static void main(String[] args) { SpringApplication.run(Test1Application.class, args); } ... ====@SpringBootApplication==== is a convience annotation that adds <code>@Configuration</code>, <code>@EnableAutoConfiguration</code>, <code>@EnableWebMvc</code> and <code>@ComponentScan</code> which enables e.g. Auto-Configuration ===Rest Controller=== import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins="http://localhost:4200") // avoid cross origin errors in browser [[SpringBoot#.40RequestMapping|@RequestMapping]]("xyz") public class HelloWorldController { // @RequestMapping(method=RequestMethod.GET, path="/hello-world") @GetMapping(path="/hello-world") @JsonView(MenuView.NodeView.class) // tells Jackson to propagate the view class to the entities for [[Glossary#JSON|json]]-fication the return value // the same annotation has to be used at attributes in the JPA entities, which should be used for this view public <METHOD>() { ... } ====@RequestMapping==== import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("xyz") // no need of backslash, all URLs of the mappings have the prefix 'xyz', method mappings need to include the / after the prefix e.g. http://localhost/xyz/do_something public class XYZControler { @GetMapping("/do_something") public void doSomething() { ... ====@ResponseBody==== The <code>@ResponseBody</code> annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. There is no need to annotate the <code>@RestController</code>-annotated controllers with the <code>@ResponseBody</code> annotation since Spring does it by default. ====Method Return Values==== public User <METHOD> public ResponseEntity<User> <METHOD> // is the same as above ===[[JavaJEEJPA|JPA]]=== * Spring Boot does not need [[JavaJEEJPA#persistence.xml|persistence.xml]] ===JPA Repository=== import org.springframework.data.jpa.repository.JpaRepository; public interface TestRepository extends JpaRepository<E1, Long> { } // in controller @Autowired TestRepository testRepo; ====Repository==== <code>JpaRepository</code> extends <code>PagingAndSortingRepository</code> which in turn extends <code>CrudRepository</code>. Their main functions are: * CrudRepository mainly provides CRUD functions. * PagingAndSortingRepository provides methods to do pagination and sorting records. * JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch. Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository, use CrudRepository. =====Query Methods===== Define the query methods in a repository interface that extends one of the Spring Data's repositories. Spring Data JPA will create queries automatically by parsing these method names. A derived query method name has two main components separated by the first By keyword: * The '''introducer''' clause like find, read, query, count, or get which tells Spring Data JPA what you want to do with the method. This clause can contain further expressions, such as Distinct to set a distinct flag on the query to be created. * The '''criteria''' clause that starts after the first By keyword. The first By acts as a delimiter to indicate the start of the actual query criteria. The criteria clause is where you define conditions on entity properties and concatenate them with And and Or keywords. =====save()===== * can be called on new or existing entities * returns the entity, if new with the id set ====General Configuration==== * configuration in [[#Application_Properties|application.properties]] spring.jpa.hibernate.ddl-auto=[none|update|create|create-drop] // none: nothing is changed in the DB, default for MySQL // update: DB structure updated according to the entities // create: DB is created on startup // create-drop: creates DB on startup, drops it on closing, default for H2 ====MariaDB==== * in pom.xml: <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <scope>runtime</scope> </dependency> * configuration in [[#Application_Properties|application.properties]] spring.datasource.url=jdbc:mariadb://localhost:3306/test spring.datasource.username=root spring.datasource.password= ====MySQL==== * in pom.xml: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> * configuration in [[#Application_Properties|application.properties]] spring.datasource.url=jdbc:mysql://localhost:3306/mysql506 spring.datasource.username=root spring.datasource.password=mHalloo0@1m ===Command Line Runner=== CommandLineRunner is a simple Spring Boot interface with a run method. Spring Boot will automatically call the run method of all beans implementing this interface after the application context has been loaded. ===Integration Test=== @SpringBootTest class BookmarksApplicationTests { @Test void contextLoads() { } } ==Build== There are two standard build tools, Maven and Yaml. mvn package // compile and put jar to target mvn -Dmaven.test.skip package // skip test generation mvn -DskipTests package // skip test execution mvn install // compile, put jar to target and put it to local repository ==Resources== * [https://start.spring.io/ Spring Initializer] * [https://spring.io/guides Spring Boot Guides] * [https://www.springboottutorial.com/ Spring Boot Tutorials by 28Minutes] * [https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html How To Guides ...] ==Hosting== ===Heroku=== * https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku * https://www.codejava.net/heroku/deploy-spring-boot-app-with-mysql * https://roytuts.com/how-to-deploy-spring-boot-data-jpa-application-to-heroku-cloud/ * https://www.youtube.com/watch?v=TixLbON3TR8 ==Examples== Some examples are not available anymore due to the loss of the Eon laptop. ===[[Heroku#Spring_Boot_Demo|Demo project local and on Heroku]]=== ===Test1=== * for Raspberry 4 # create app with Sprint Initialzr [[File:SpringBootTest1_1.PNG|400px]] # copy test1.zip to <code>C:\Uwes\eclipse\workspace_2020-12\SpringBoot</code> # extract it, which creates a test1 directory # import as Maven project and select root directory ===Test2=== * for Raspberry * export productive DB content of DB mysql506 via https://uweheuer.spdns.de/phpxmyadmin to C:\Uwes\Backup\Raspberry (incl. drop statements) * import after starting xampp via http://localhost:8090/phpmyadmin Then # use wizzard of [[Eclipse#Spring_Tools|Eclipse Spring Tools]] # File -> New -> Other -> Spring Starter Project # [[File:SpringBootTest2_1.PNG|400px]] # [[File:SpringBootTest2_2.PNG|400px]] # in order to use JPA Tools (according to [https://stackoverflow.com/questions/50817803/jpa-tools-menu-missing-from-eclipse here]) right click project -> Configure -> Convert to JPA Project ## [[File:SpringBootTest2_3.PNG|400px]] ## [[File:SpringBootTest2_4.PNG|400px]] # RC project -> JAP Tools -> Generate entities from tables # Run As 'Spring Boot App' ===Test3=== * creation with eclipse wizzard like [[#Test2|Test 2]] * identified ** not encrypted urls in productive DB ** change to menu can be null, because urls can exist w/o menu (set by PHPAdmin in DB) ===Udemy Course=== * [[File:SpringBoot2.PNG|800px]] * start eclipse * File -> Import -> Maven Project ===Bookmarks=== * [[File:SpringBootBookmarks.PNG|400px]] * start eclipse * File -> Import -> Maven -> Existing Maven Projects * select <code>C:\Uwes\eclipse\workspace_2020-12\SpringBoot\bookmarks</code> ====Database Configuration==== The default is that the datasource url is generated randomly and printed to the console. The default user is 'sa', default password is empty. * in [[#Application_Properties|application.properties]] spring.profiles.active=[dev|laptopmysql|raspberry] * and created in <code>\bookmarks\src\main\resources\</code> dedicated property files <code>application-[dev|laptopmysql|raspberry].properties</code> =====H2 Database Configuration===== * see <code>application-dev.properties</code> # to make the h2 database url constant, otherwise it is a random url spring.datasource.url=jdbc:h2:mem:bookmarksdb # user and password for H2 console spring.datasource.username=uwe spring.datasource.password=uwe =====Test Data for Startup===== * in <CODE><PROJECT_DIR>/src/main/resources/data.sql</CODE> ====Links==== * see My Bookmarks -> Web-Präsenz -> localhost -> SpringBoot -> Bookmarks ====ToDos==== * JSON rest APIs ** [https://www.logicbig.com/tutorials/misc/jackson/json-identity-info-annotation.html @JsonIdentityInfo] ** [https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring @JSonView] * adjust maven build ** https://riptutorial.com/spring-boot/example/31100/set-the-right-spring-profile-by-building-the-application-automatically--maven- * build entities **The @ManyToOne association uses FetchType.LAZY because, otherwise, we’d fall back to EAGER fetching which is bad for performance. * https://thorben-janssen.com/ultimate-guide-derived-queries-with-spring-data-jpa/ Query Documentation] ** Sorted Lists *** http://assarconsulting.blogspot.com/2009/08/why-hibernate-does-delete-all-then-re.html *** https://stackoverflow.com/questions/13101882/jpa-onetomany-list-vs-set/29562678 *** https://www.google.com/search?q=jpa+onetomany+list+or+set&rlz=1C1GCEU_deDE848DE867&ei=-iFTYO3XHJWj1fAPw5mgqAM&oq=JPA+%40one2many+list&gs_lcp=Cgdnd3Mtd2l6EAEYATIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeOgcIABBHELADOggIABAWEAoQHlDLIViCJWC1UmgCcAJ4AIABhgGIAdkDkgEDNC4xmAEAoAEBqgEHZ3dzLXdpesgBCMABAQ&sclient=gws-wiz
Summary:
Please note that all contributions to Wiki RB4 may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Uwe Heuer Wiki New:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Toggle limited content width