1springBoot Project Mapping method,
1, integrating parent project
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
2, Write Dependencymanagement
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.8.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2 Springboot Start-up
1 springapplication application = new Springapplication ();
set<object> set = new hashset<> ();
Set.add (Main.class);
Application.setsources (set);
Configurableapplicationcontext context = Application.Run (args);
2 Configurableapplicationcontext context = Springapplication.run (Main.class, args);
3 Springboot startup will be Sources as a configuration class, quite a @SpringBootConfiguration annotations, so you can not write @springbootconfiguration
The default profile for the 4 Springboot is application.properties
4 Springboot Three ways to get configuration files
1, go back to environment object through context
Context.getenvironment (). GetProperty ("Local.port")
2, inject Environment object
@Autowired
private environment environment;
3, use @Value ("${local.ip}") to inject the property above
Note: value format ${key}
5 springboot propertise Configuration supports internal references (you can approach the value of the application key directly in value via an expression)
local.ip=127.0.0.1
local.port=8080
Local.ipandport=${local.ip}:${local.port}
6 configuration file go to default value (if key does not exist and no default or error is set) but Getenvironment (). GetProperty ("Local.def", "000000") this way gets no error, only returns null
${key: Default Value} (takes effect without this key)
Example: @Value ("${local.df:99}") (Local.df does not exist)
7 Modifying the location of the configuration file
Default profile is classpath: root directory or classpath:config/directory
8 Modifying the profile name
1 Modify Main method start parameter--spring.config.name= configuration file name (do not extend name)
2 Modify any path and file name--spring.config.location=classpath:conf/app.properties
3 can be file: The address of the Protocol--spring.config.location=file:d:\eclipsej2ee\springboot\src\main\resources\conf\app.properties
4 can have multiple configuration files (Comma separated)-spring.config.location=file:path,classpath:path2,,classpath:path2
5 The path to the configuration file can be specified by @PropertySource ("classpath:conf/app.properties") annotation
Note: @PropertySources can write multiple @PropertySource
Note 2: You can write multiple @PropertySource directly
6 using @ConfigurationProperties (prefix= "local") to specify the configuration file directly
Note: If the key does not have a prefix, then do not configure the prefix can
The 9,springboot configuration file allows the YML
10, inject set or array (pro-test, necessary to specify generic type), cannot be set
Key[0]=value0
Key[1]=value1
Key[2]=value2
11 dynamically specifying the configuration file programmatically requires implementing the Environmentpostprocessor interface and registering it in the Meta-inf/spring.factories
Spring.factories-org.springframework.boot.env.environmentpostprocessor= Com.zyk.springBoot.main.MyEnvironmentPostProcessor
Code implementation environment.getpropertysources (). AddLast (Propertysource); Propertysource seems to be the placehoder of spring.
Spring's profile
12 Specifying Profile
The default is to load the Application.properties settings class App.setadditionalprofiles ("test"); Additional application-test.properties will be loaded, if the test environment configuration and the default environment configuration have key duplication, then with the additional, if the array, will not be merged, but only with the additional environment
Note: Setadditionalprofiles set up additional profiles (multiple additional configurations can be added)
Note 2:--spring.profiles.active=test can also set the environment (additional activation)
Note 3:--spring.profiles=test only activates test, does not activate the default environment
A Bean that is @Profile modified will take effect only if the specified environment surface (can be specified before the type)
Spring's Condition
Condition interface with the use of @Conditional annotations, decoration @bean only if the condition is set, Spring will call @bean method,
Custom condition Examples:
@Bean
@Conditional (Mycondition1.class)
Public String GBK () {
return "GBK";
}
@Bean
@Conditional (Mycondition2.class)
Public String UTF () {
return "Utf-8";
}
Only when the method of the Mycondition2.class interface function is put back to true will it produce
Spring provides a large number of default condition annotations
Note 1: All conditions are required for @Conditional to be established true
Note 2: @Conditional have a large number of annotations similar to @ConditionalOn *, which are only transferred when they are satisfied @Bean
@ConditionalOnBean
@ConditionalOnClass
@ConditionalOnJava
@ConditionalOnExpression
@ConditionalOnNotWebApplication
@ConditionalOnSingleCandidate
Spring @Enable * Annotations
1, @EnableAsync after the annotation is turned on using asynchronous run, the method @Async adornment executes asynchronously (not the proxy object, estimating that spring is the binary code that changed the method directly)
@Import import a class that requires spring management (either a configuration class or a generic bean)
Note: @Import can point to the implementation class of the Importselector interface, specifying the imported class in the interface function (interface and method return value is the class name full character array)
Note 2: The implementation class that can write Importbeandefinitionregistrar is used to register the bean
The features of spring annotations, any custom annotations written to the spring configuration class, the entire parent annotation (Spring-aware) of this custom annotation will take effect (n-tier is in effect)
The function of the @EnableAutoConfiguration (Classpath below the meta-inf inside the Spring factory file inside the interface corresponding values are added to the spring management)
1, you can write the org.springframework.boot.autoconfigure.enableautoconfiguration=com.zyk.springboot.parent in the Meta-inf.
This way spring will add the parent to spring management (if the parent is a class join management, if the parent is the same configuration), and the configuration of the above statement can be used by another Jar (other Project module) package
Note 2: This annotation can be enabled or closed via Spring.boot.enableautoconfiguration=ture/false (you can uninstall the Application.properties configuration file or args)
Springboot event listener needs to inherit applicationevent, implement Myapplicationlistener, need to register the listener first, and then publish the event
Example:
springapplication App = new Springapplication (main.class);
App.addlisteners (New Myapplicationlistener ());
Configurableapplicationcontext context = App.run (args);
Enable this listener needs to be enabled in order to accept events, the boot can be started by
1 any way the listener joins the spring container (as a normal bean can be added)
2 in springapplication app = new Sp Ringapplication (Main.class); App.addlisteners (New Myapplicationlistener ());
3 Write Context.listener.classes=com.zyk.springboot.event.myapplicationlistener in configuration file application.properties (This method is related to Delegatingapplicationlistener)
4 can not implement Applicationlistener directly in a method to write the annotation @EventListener (parameters determine what type of event can be accepted, The argument type is arbitrary, Object can accept any type) (related to the Eventlistenermethodprocessor process Class)
@EventListener
public void Listener1 ( Myapplicationevent event) {
System.out.println ("Receive directly:" + Event.getsource ());
}
5 in the factory config file go to org.springframework.boot.springapplicationrunlistener= .....
Expansion analysis of Springboot
is a way to implement an interface Applicationcontextinitializer and then add it to the container springapplication.addinitializers (new Myapplicationcontextinitializer ()); There are springcontext in this interface function that can do something during container startup.
Note 1: cannot be added directly to the spring container (should be this very early, do not want event listener)
Note 2: The container-managed class is not loaded at this time and cannot be taken to the spring-managed class (only the first 6 classes)
Second way configuration file configuration Context.initializer.classes=com.zyk.springboot.event.myapplicationcontextinitializer
The third type: write in the factory config file to org.springframework.context.applicationcontextinitializer= ...
Commandlinerunner the last step of the container to start successfully (more than Applicationcontextinitializer), when the container has been started
1 notes directly into the container will take effect
[Email protected] (100) Modification order (after the large number of the execution)
Applicationrunner similar (the Applicationrunner parameter is the applicationarguments package), Commandlinerunner obtains the original value of the args of main
22 Close the Springboot banner App.setbannermode (Banner.Mode.OFF);
@SpringBootApplication The default scan is the current package, and the child package can specify the scan package via Scanbasepackages
24 Custom Banner Write a banner.txt located in Classpath will brake using this file inside the banner
25 Specify the encoding by writing banner.location in the configuration file to specify banner location Banner.cherset
The banner of the expenditure picture of spring is named as banner. Picture format can be
Banner.img.location Specified location
Analysis of running flow of springboot
No record.
Springboot Web aspects
@RestController similar to @controller, the difference is that it is equivalent to writing @ResponseBody in each method (Springweb with not springboot Exclusive) (after 4.0)
29 provides a large number of annotations such as @GetMapping to replace @RequestMapping each time you need to specify method (after 4.3)
Springboot specify prefix and suffix (springboot default does not support JSP, need to be mapped into tomcat-embed-jasper to support)
spring.mvc.view.prefix=/web_inf/jsp
spring.mvc.view.suffix=.jsp
31 Specify Port server.port=8080
32 Delivery of parameters to Page view the traditional way is by setting properties in Reques, which can now be done by Model or Modelandview
Springboot using Freemarker (test not successful,)
34 access to static resources related to ResourceProperties, which defines which directories can be accessed directly
Spring.resources.staticlocations= .... can modify
35 after using the @servletcomponentscan annotation on springbootapplication, the Servlet, Filter, Listener can be passed directly through @WebServlet, @WebFilter, @ Weblistener annotations are automatically registered without additional code. This only supports servlet3.0 later
or through Servletregistrationbean (this can support servlet2.5 before)
@Bean
Public Servletregistrationbean Servletregistrationbean () {
return new Servletregistrationbean (new Myservlet (), "/xs/*");
}
Note: There are also Filterregistrationbean Servletlistenerregistrationbean
36 start with jetty, need to exclude Tomcat and then join (do not rule out as if it can)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Spring-boot-autoconfigure/1.5.8.release/spring-boot-autoconfigure-1.5.8.release-sources.jar There are a lot of configuration can refer to
Use Interceptors (handlerinterceptor,webmvcconfigureradapter) inside the PNS Springboot
The steps are as follows:
1 Write a class implementation handlerinterceptor
2 Write a class integrated Webmvcconfigureradapter
3 adding interceptors to the Webmvcconfigureradapter method
38 Custom Exception Handling
1 Way 1 (springboot only)
Implement Errorpageregistrar (need to add to Spring Management) (ErrorPage objects can correspond to different status codes, different exceptions jump to different addresses (this address can be a page or action))
Add the relationship of ErrorPage corresponding exception and exception handling address in Errorpageregistrar
Mode 2 uses the Simplemappingexceptionresolver class and joins the spring management
Mode 3 uses the implementation of the Handlerexceptionresolver interface and joins the spring management
Mode 4 @ExceptionHandler Annotation method (the default is to handle only the current controller inside of your exception, before the class plus @ControllerAdvice can handle all exceptions, the priority is lower than the definition of the same control class)
The role of the @ControllerAdvice
The method of using @exceptionhandler, @InitBinder, @ModelAttribute annotations inside the @controlleradvice annotations is applied to all @RequestMapping annotations. But only if the use of @exceptionhandler is most useful, the other two are of little avail.
40 inheritance Embeddedservletcontainercustomizer can be set for the start of a servlet container
Method 2 Returns a Embeddedservletcontainercustomizer object directly on the @bean
41 Implementation Abstractroutingdatasource can switch to a spring data source (spring will go to this to fetch the data source)
Springboot Knowledge points