springboot (use)

springboot (use)

 

The automatic configuration of springboot is to automatically integrate the corresponding framework after the introduction of the started jar. If no additional code coverage is required, the default configuration of this framework will be used, and the automatically assembled framework will be

There is a default configuration ( @EnableAutoConfiguration ) ( the configured file class is assembled, the default file class )

 

After modification, you need to right-click on build.gradle to refresh

 

@Configuration configuration class

@Import import class

@ComponentScan collects all spring classes including @Configuration search beans, and combines @Autowired constructor injection.

If you put the main application class in the root directory, @componentScan does not need any parameters to collect all ( @Component , @Service , @Repository , @Controller etc.)

@ImportResource loads xml

EnableAutoConfiguration or add @SpringBootApplication to a @Configuration class to select auto-configuration.

Automatic configuration according to the loaded jar dependencies, and automatic configuration of @Configuration classes

 

@SpringBootApplication=@Configuration , @EnableAutoConfiguration 和 @ComponentScan

 

 

--debug startup can see the current automatic configuration

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) disables custom configuration and excludes the corresponding main class

 

java -jar 运行jar

java -jar target/myproject-0.0.1-SNAPSHOT.jar

 

You can set the jar package to run remotely (enable remote debugging), and debug locally

$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \

-jar target/myproject-0.0.1-SNAPSHOT.jar

 

CommandLineRunne command line startup is to specify the code to be executed immediately after the application starts (if there are more than one, the execution order can be set) to implement this interface

 

 

 

Externalized configuration:

i.e. a reference to the parameter

Using the @Value annotation, you can directly inject attribute values ​​into your beans. You don't have to configure the tool class springboot yourself. If you simply use spring, you need to accompany it.

 

Override order:

Spring Boot uses a very specific PropertySource order to allow reasonable overriding of values, properties need to be considered in the following order: (higher priority)

1. Command line parameters

2. JNDI properties from java:comp/env

3. Java system properties (System.getProperties())

4. Operating system environment variables

5. Only properties contained in random.* will generate a RandomValuePropertySource

6. Application configuration file outside the packaged jar (application.properties, containing YAML and profile variables)

7. Application configuration file (application.properties, containing YAML and profile variables) inside the packaged jar

8. @PropertySource annotation on @Configuration class

9. Default properties (specified using SpringApplication.setDefaultProperties)

 

import org.springframework.stereotype.*

import org.springframework.beans.factory.annotation.*

@Component

public class MyBean {

@Value("${name}")

private String name;

// ...

}

 

 

 

Inject random values:

my.secret=${random.value}

my.number=${random.int}

my.bignumber=${random.long}

my.number.less.than.ten=${random.int(10)}

my.number.in.range=${random.int[1024,65536]}

 

 

 

 

You can put parameters into the spring environment through the command line, or you can put the configuration into the spring environment through the application.properties file

 

The properties file can be configured with multiple, the same name or different names, with different priorities in different paths

1. A /config subdirectory in the current directory

2. Current directory

3. A /config package on the classpath

4. classpath root path (root)

This list is ordered by priority (higher positions in the list will override lower ones).

 

This configuration file can use the value of this configuration file (${})

 

 

 

 

Personalization overrides for autowiring, exclusions

cover,

1. Re-inject the same class (because the id used by springboot in the default configuration is based on the class name. When we use the same class, the name is naturally the same, which overrides the default configuration)

 

If you don't want to override the executor's access rules, you can use

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) annotate the bean, otherwise use

@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)注解该bean。

 

Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses. Reasonable defaults are included out of the box, e.g.

Objects can be automatically converted to JSON (using the Jackson library) or XML (using the Jackson XML extension if it is available, otherwise using JAXB). string

UTF-8 encoding is used by default.

If you need to add or customize converters, you can use Spring Boot's HttpMessageConverters class:

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;

import org.springframework.context.annotation.*;

import org.springframework.http.converter.*;

@Configuration

public class MyConfiguration {

@Bean

public HttpMessageConverters customConverters() {

HttpMessageConverter<?> additional = ...

HttpMessageConverter<?> another = ...

return new HttpMessageConverters(additional, another);

}

}

Any HttpMessageConverter bean present in the context will be added to the converters list, you can override the default converter this way

(converters)。

26.1.2.

 

 

2,

 

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) disables custom configuration and excludes the corresponding main class

 

 

Static content:

 

 

The entire standard of webappz will only work when it is marked as war. If it is to be marked as a jar package, this will not work. Springboot will use the /static (/public, /resources or /META-INF/resources) file under the classpath.

or servletcontext root to serve static content

 

When you use any of these engines with the default configuration, your templates will be automatically loaded from the src/main/resources/templates directory.

 

The current jar package does not contain the static files under the webapp, how can I get it? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

 

 

3, @EnableWebSecurity closes the default configuration through the label; reconfigures the new configuration

@EnableWebSecurity bean to completely turn off Spring Boot's default configuration. In order to customize it, you need to use

External property configuration and beans of type WebSecurityConfigurerAdapter (for example, to add form-based login)

 

 

 

 

 

Statically inject configuration files into bean properties:

1,@Value

2, @ConfigurationProperties(prefix="connection") All prefixes are connections are placed in the bean's property of the same name

@Component

@ConfigurationProperties(prefix="connection")

public class ConnectionSettings {

private String username;

private InetAddress remoteAddress;

// ... getters and setters

}

 

References in other classes:

@Autowired

private ConnectionSettings connection;

 

 

Injection via @EnableConfigurationProperties

@Configuration

@EnableConfigurationProperties(ConnectionSettings.class)

public class MyConfiguration {

}

 

 

You can set an embedded servlet container, and different containers have limited support for jsp

 

 

Spring Data provides an additional feature to create Repository implementations directly from interfaces,

spring data jpa is the generated entity

Traditionally, JPA entity classes are defined into a persistence.xml file. In Spring Boot, this file is not required and is replaced by 'Entity Scan'. silent

By default, all packages under your main configuration class (classes annotated with @EnableAutoConfiguration or @SpringBootApplication) will be

Find. (@EnableAutoConfiguration scans the package where the main class is located and all subpackages)

 

 

Use of configuration files:

Map property values ​​in configuration files to beans

1. Through the prefix, and the attribute of the corresponding name in the bean, the attribute of the same name in the configuration file is automatically injected by get, set, and then directly obtained through get, set (type-safe configuration attribute) can be loosely bound

@Component

@ConfigurationProperties(prefix="connection")

public class ConnectionSettings {

private String username;

private InetAddress remoteAddress;

// ... getters and setters

}

 

# application.yml

connection:

username: admin

remoteAddress: 192.168.1.1

# additional configuration as required

 

 

loose binding

 

@Component

@ConfigurationProperties(prefix="person")

public class ConnectionSettings {

private String firstName;

}

 

person.firstName standard camel case

person.first-name is indicated by the dotted line and is recommended for use in .properties and .yml files

PERSON_FIRST_NAME uppercase, recommended when using system environment variables

 

 

 

2. Directly specify a property file source, the bean does not need the property name, and then operate the property file by operating the bean (third-party configuration)

 

@Configuration

@ConfigurationProperties

@PropertySource("classpath:paprocesser.properties") //Only applicable to .properties, not yml

public class ProcesserProperty extends Properties{

 

}

//or

@ConfigurationProperties(prefix = "foo")

@Bean

public FooComponent fooComponent() {

...

}

 

 

paprocesser.propertie

1310=inMoneyProcesser

 

 

//Obtain

String processerBeanName = processerProperty.getProperty("1310");

 

 

3. Take it directly with @Value("${pa.url}")

 

 

@Value("${pa.url}")

private String paUrl ;

 

 

 

 

 

 

 

 

 

Autowiring also means instantiating the beans needed in the autoconfiguration

These beans can be injected through the set when they are used, or they can be injected through the constructor

 

 

 

You can inject an auto-configured org.springframework.data.mongodb.MongoDbFactory to access the Mongo database.

 

 

public class MyBean {

private final MongoDbFactory mongo;

 

@Autowired//Constructor injection

public MyBean(MongoDbFactory mongo) {

this.mongo = mongo;

}

 

 

Trigger for autowiring:

Spring Boot configures a ConnectionFactory if ActiveMQ is found to be available on the classpath. If a proxy is required, an embedded one will be enabled,

A proxy that has been automatically configured (as long as the proxy URL is not specified in the configuration).

 

 

 

 

 

jmx is equivalent to jconsle

Which beans need to be monitored and managed in spring, you only need to add annotations to this class, and the framework will automatically export the monitored beans after scanning these annotations (springboot integrates jmx as long as you import the jmx package and use it directly. Can)

, in ordinary spring, you need to configure jmx @ManagedResource, @ManagedAttribute, @ManagedOperation)

 

 

 

 

 

 

 

test:

Use annotated test classes (dependency injection, you can directly use the beans in the spring container, otherwise you won't get the context)

1, run through the application

 

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)

public class CityRepositoryIntegrationTests {

@Autowired

CityRepository repository;

// ...

}

 

2. Running in web mode, verified by http request (add @WebIntegrationTest on the basis of one)

 

 

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)

@WebIntegrationTest

public class CityRepositoryIntegrationTests {

@Autowired

CityRepository repository;

RestTemplate restTemplate = new TestRestTemplate();

// ... interact with the running server

}

 

 

 

 

 

 

 

 

server.context-path=/settlement

 

 

 

 

 

 

RestTemplate is actually an address-based request client that encapsulates the original httpclient

 

 

Introduction of new modules: (a package)

1, **config.java// is equivalent to the configuration file of the framework, ready to configure the class

@Configuration

public class PaConfig {

 

@Bean

public RestTemplate restTemplate(){

RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();

 

RestTemplate paTemplate = restTemplateBuilder.build();

 

paTemplate.getMessageConverters().clear();

paTemplate.getMessageConverters().add(new PaHttpMessageConverter());

return paTemplate;

 

}

}

 

 

 

 

2. Prepare the classes that need to be configured in 1

 

3. Use classes

 

 

 

 

 

 

 

 

thymeleaf template

In addition to the general springmvc's own view resolver function, there is also the function of automatic switching between static and dynamic

 

http://www.open-open.com/lib/view/open1451625468230.html

 

 

The idea of ​​using the template after encapsulation:

<!-- Scans the classpath of this application for @Components to deploy as beans -->

       <context:component-scan base-package="com.test.thymeleaf.controller" />

 

       <!-- Configures the @Controller programming model -->

       <mvc:annotation-driven />

 

        <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->

        <!--springMVC+jsp jump page configuration-->

       <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->

              <!--<property name="prefix" value="/WEB-INF/views/" />-->

              <!--<property name="suffix" value=".jsp" />-->

       <!--</bean>-->

 

       <!--springMVC+thymeleaf jump page configuration -->

       <bean id="templateResolver"          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">

         <property name="prefix" value="/WEB-INF/views/" />

         <property name="suffix" value=".html" />

         <property name="templateMode" value="HTML5" />

       </bean>

 

       <bean id="templateEngine"           class="org.thymeleaf.spring4.SpringTemplateEngine">

          <property name="templateResolver" ref="templateResolver" />

       </bean>

 

       <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">//////spring provides an automatically encapsulated class thymeleaf-spring4-2.1.4.RELEASE.jar

         <property name="templateEngine" ref="templateEngine" />

       </bean>

 

thymeleaf-2.1.4.RELEASE.jar the entire template framework

thymeleaf-spring4-2.1.4.RELEASE.jar//spring provides automatically encapsulated classes

 

//A static property and a dynamic property

<img src="../../static/assets/images/qr-code.jpg" th:src="@{${path}}" alt="二维码" />

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />

 

-- Simple data conversion (number, date)

 

   <dt>价格</dt>

    <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>

   <dt>Date of Receipt</dt>

   <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>

-- string concatenation

 

<dd th:text="${'$'+product.price}">235</dd>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326295150&siteId=291194637
Recommended