preface

Spring Boot is a new framework from the Pivotal team designed to simplify the initial setup and development process for new Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations.

Java Learning Notes Sharing address: Spring Boot core technology over 100 pages of learning notes

Spring Boot is considered the “successor” to Spring MVC. It can automatically configure for us, and if the default configuration does not meet our requirements, we can replace the auto-configuration class and use our own configuration. In addition, Spring Boot also integrates embedded Web servers, system monitoring, and many other useful features, allowing us to quickly build enterprises and applications.

1. @ Conditional

You can control more complex configuration conditions. If Spring’s built-in condition control annotations do not meet application requirements, you can use this annotation to define your own control conditions to meet your own requirements.

Example:

@Conditioanl(CustomConditioanl.class)
CustomProperties addCustomProperties(){
 / /...} /2,Copy the code

2, @ ConditionalOnResource

This is the code that uses this annotation to detect the method that triggers the annotation when a configuration file is enabled

Example:

@ConditionalOnResource(resources = "classpath:website.properties")
Properties addWebsiteProperties(){
 / /...
}
Copy the code

3, @ ConditionalOnClass and @ ConditionalOnMissingClass

These two annotations are class-conditional annotations that determine whether certain configurations should be performed based on the presence or absence of a class.

Example:

@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoConfiguration {
 / /...
}
Copy the code

4, @ SpringBootApplication

An annotation is a quick configuration annotation that allows one or more beans to be defined in a class that is annotated and automatically triggers automatic configuration of beans and automatic scanning of components. This annotation is equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan.

This annotation is used in the main class of the Spring Boot application.

Example:

@SpringBootApplication
public class Application{
 public static void main(String [] args){ SpringApplication.run(Application.class,args); }}Copy the code

5, the @autowired

The @AutoWired annotation is used to mark dependencies that Spring will resolve and inject. This annotation can be applied to constructors, fields, and setter methods, applied to constructors

Example:

@RestController
public class userController {
	private UserService userService;
	@Autowired
	UserController(userService userService){
		this.userService = userservice; }}Copy the code

6, @ Primary

When multiple beans of the same type need to be configured in the system, @primary can define the priority of these beans.

Example:

7. Scops notes

The @scope annotation can be used to define the Scope of the classes tagged with the @Component annotation and the Scope of the classes tagged with the @Bean. The Scope of @scope is: Singleton, Prototype, Request, Session, globalSession, or any custom Scope. Prototype is used as an example.

When a Spring Bean is declared prototype, the Spring IoC container initializes a new instance of the modified class each time the class needs to be used. When defining a Bean, you can set the scope property of the Bean to

Prototype: scope = "prototype"Copy the code

You can also set it using the @scope annotation

@Scope(value=ConfigurableBeanFactory.SCOPE_PROPTOTYPE)
Copy the code

There are two different ways to use the @scope annotation, for example:

8, @ RequestBody

Used in the argument list of the processing request method, it binds the parameters in the request body to an object. The request body parameters are passed through HttpMessageConverter, matching and binding values based on the parameter names in the request body to the attribute names of the object. In addition, parameters in the request body can be validated using the @valid annotation.

Example:

9, @ PostMapping

The @postMapping annotation is used to process HTTP POST requests and map requests to specific processing methods. @postMapping, like @getMapping, is a composite annotation that works as a shortcut to @requestMapping (method= httpmethod.post).

Example:

10, @ DeleteMapping

The @deletemapping annotation is used to process HTTP DELETE requests and map them to DELETE methods. @deletemapping is a composite annotation that is equivalent to a shortcut to @requestMapping (method= httpmethod.delete).

Example:

11, @ ResponseBody

@responseBody automatically writes the return value of the method in the controller to the HTTP response. Specifically, the @responseBody annotation can only be used in a class marked by the @Controller annotation. If you are in a class marked by @RestController, the method does not need to be annotated with the @responseBody annotation. @restController is kind of a combination annotation of @Controller and @responseBody.

Example:

12, @ ResponseStatus

Annotations can mark the request handling method. Using this annotation, you can specify the HTTP STATUS required for the response. In particular, we can assign the value attribute of the annotation using the HttpStauts class.

Example:

13, @ RequestParam

Annotations are used to bind the parameters of a method to the parameters passed in the Web request. You can easily access the values of HTTP request parameters using @requestParam.

Example:

14, @ Controller

Is an extension of the @Component annotation that automatically scans and configures the classes annotated by the annotation. This annotation is used to annotate the Spring MVC controller.

Example:

15, @ ModelAttribute

Models that already exist in the controller can be accessed through the model index name

Example:

As with the @pathVariable and @RequestParam annotations, you do not need to specify an index name if the parameter name has the same name as the model, as in the following shorthand:

If you annotate a method with @ModelAttribute, Spring binds the return value of the method to a specific Model

Example:

All methods annotated by the @ModelAttribute annotation will be executed before Spring invokes the specific processing method.

16, @ Component

Annotations are used to annotate a common component class that has no clear business scope and simply informs Spring that the annotated class needs to be incorporated into the Spring Bean container and managed.

Example:

17, @ the Repository

The @Component annotation is an extension of the @Component annotation. Like the @Component annotation, classes annotated by this annotation are automatically managed by Spring. The @Repository annotation is used to annotate DAO layer data persistence classes.

Example:

18, @ DependsOn

The Spring IoC container can be configured to initialize other Bean objects before initializing one Bean

Example:


Spring Boot returns JSON data

Before doing the following, we make a simple change to Hello. We create a package com.hpit.test.web and create a class HelloControoler, and then modify the app. Java class.

The main code is as follows:

iackage com.hpit; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** * Hello world! * /

// The @springBootApplication declaration tells SpringBoot to automatically configure the program as necessary, equivalent to using the default properties
@Configuration, @enableAutoConfiguration, and @ComponentScan
//@SpringBootApplication
public class App {
public static void main(String[] args){ SpringApplication.run(App.class, args); }} com. Hpit. Test. Web. HelloController: package com. Hpit. Test. The web;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController// The label is restful
public class HelloController {
@RequestMapping("/")
public String hello(){
return"Hello world!"; }}Copy the code

When writing an interface, we often need to return JSON data, so how to do in Spring Boot? Mostly in class

Add the annotation @restController.

Steps to return JSON:

(1) Write an entity class Demo

(2) Write DemoController;

(3) Add @restController and @requestMapping annotations to DemoController;

(4) test

The specific code is as follows:

com.hpit.test.bean.Demo :
package com.hpit.test.bean;
/** * Tests the entity class@author Administrator* * /
public class Demo {
  private longid;/ / the primary key.
private String name;// Test name.
public long getId() {
returnid; }
public void setId(longid) {
this.id = id; }
public String getName() {
returnname; }
publicvoid setName(String name) {
this.name = name; }} com. Hpit. Test. Web. DemoController: package com. Hpit. Test. The web;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hpit.test.bean.Demo;
/** * test. *@author Administrator* * /
@RestController
@RequestMapping("/demo")
public class DemoController {
Request/return the demo data: * * * * address: http://127.0.0.1:8080/demo/getDemo *@return* /
@RequestMapping("/getDemo")
public Demo getDemo(){
  Demo demo = new Demo();
demo.setId(1);
demo.setName("Zjs");
returndemo; }}Copy the code

So in the browser to access the address: http://127.0.0.1:8080/demo/getDemo returned the following data: {id: 1, name: “Zjs}”

Spring Boot also references Jackson’s JSON parsing package, so naturally we can use Jackson’s ANNOTATIONS on the Demo object, format the time, ignore some fields, and so on.

Spring Boot Imports the Spring XML configuration file

Write HelloService2 in the app. Java class;

First we have a few bags here: Com. hpit,org.hpit, we are going to put the app. Java startup class in com.hpit, according to the SpringBoot scan (root to subpackage rule), we are going to write HelloService2 in the SpringBoot can scan, HelloService is written in a location that Spring Boot cannot scan, so we use the configuration file bean to import, the specific code is as follows:

1. Create a bean that the App cannot scan by default

package org.hpit.demo.service;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
/** * TODO the current class cannot be scanned by App will be configured in applicationContext.xml *@author Zheng Jiangshan * */
@Service("helloService")
public class HelloService {
private Logger logger = Logger.getLogger(getClass());
public void hello() {
logger.info("This bean is not scanned by springBoot by default."); }}Copy the code

2. Create the spring traditional configuration file applicationContext.xml(whatever name you want) under resource.

src/main/resource/applicationContext.xml

<? xml version="1.0" encoding="UTF-8"? ><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<! Hosting beans that Spring Boot cannot scan by default in a traditional Spring configuration file <bean id="helloService" class="org.hpit.demo.service.HelloService"></bean>
</beans>
Copy the code

3. Create a system startup task class to test whether the Bean that App cannot scan can be assembled automatically

com.hpit.springboot03.runner.TestXMLBeanRunner

package com.hpit.springboot03.runner;
import javax.annotation.Resource;
import org.hpit.demo.service.HelloService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/** * TODO tests whether a Bean that the App cannot scan can be introduced@author Zheng Jiangshan * */
@Component
@Order(value = 1)
public class TestXMLBeanRunner implements CommandLineRunner { @Resource
private HelloService helloService;
@Override
public void run(String. arg0) throws Exception { helloService.hello(); }}Copy the code

4. Configure the @importResource annotation to import the configuration file in app.java

package com.hpit.springboot03;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource; @SpringBootApplication
@ServletComponentScan // Start servlet scanning
@ComponentScan(basePackages = { "com.hpit" })
@ImportResource(locations = { "applicationContext.xml" }) // Import the Spring configuration file
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args); }
// Config file upload @bean
public MultipartConfigElement multipartConfigFactory() {
MultipartConfigFactory configFactory = new MultipartConfigFactory();
configFactory.setMaxFileSize("128MB");// KB MB Sets the size of a single uploaded file
configFactory.setMaxRequestSize("1024MB");
configFactory.setLocation("/");// Set the file upload path
returnconfigFactory.createMultipartConfig(); }}Copy the code

5. Start the application and observe the log output. It is found that the system can import beans that the App cannot scan