Springboot Project (i)

Source: Internet
Author: User

I. Project creation 1, Idea Creation Springboot Project 1.1, File-->new-->project

Note: Idea needs to select the final version of the community version without the spring Initializ option.

SDK Select Java default, URL selection default.

1.2. Configuration Name

1.3, choose the technology commonly used, because it is a Web project, so here only select the web.

1.4. Project explanation

The 1.DemoApplication class is the entry class for the entire project, and this class has a @springbootapplication annotation, which is the core annotation of spring boot. Its purpose is to enable automatic configuration of Spring boot. OK, so I add a @restcontroller annotation to this class, make it a controller, and then provide an address translation method, as follows:

1  PackageCom.hsbc.demo;2 3 Importorg.springframework.boot.SpringApplication;4 Importorg.springframework.boot.autoconfigure.SpringBootApplication;5 Importorg.springframework.web.bind.annotation.RequestMapping;6 ImportOrg.springframework.web.bind.annotation.RestController;7 8 @RestController9 @SpringBootApplicationTen  Public classDemoApplication { One  A      Public Static voidMain (string[] args) { -Springapplication.run (demoapplication.class, args); -     } the@RequestMapping (value = "/", produces = "text/plain;charset=utf-8")) - String Index () { -         return"Hello Spring boot!"; -     } +}
1.5, run the project, browser input localhost:8080

Thus, a simple Springboot project has been established.

Entry class and @springbootapplication annotations

As I said earlier, our new project system will help us create an entry class called Artifactid+application, which has a main method, which is the entry method for a standard Java application. And here's the @springbootapplication is a combination of annotations, we can look at its source:

1 @Target ({elementtype.type})2 @Retention (retentionpolicy.runtime)3 @Documented4 @Inherited5 @SpringBootConfiguration6 @EnableAutoConfiguration7 @ComponentScan (8Excludefilters ={@Filter (9Type =Filtertype.custom,TenClasses = {Typeexcludefilter.class} One )} A ) -  Public@Interfacespringbootapplication { -  the}

We can see that it combines @springbootconfiguration, @EnableAutoConfiguration, and @componentscan, We can use these three annotations together if we do not use @springbootapplication in the development process. Of these three annotations, @SpringBootConfiguration is actually the @configuration annotation mentioned in the previous few blogs, indicating that the class is a configuration class, @EnableAutoConfiguration means that the spring The boot is automatically configured for the current project based on the jar package dependencies in the Classpath, and the last @componentscan I will not repeat, the only thing to note is that if we use @springbootapplication annotations, The system will go to the class's peer package and the sub-package to scan the entity class, so we recommend that the location of the Ingress class is under the package name of the Groupid+arctifactid combination.

To turn off specific automatic configurations

In the above section we see that the @componentscan annotation has a filter, and if we just want to @springbootapplication to scan a particular class instead of all the classes, we can turn off the automatic configuration as follows:

@SpringBootApplication (exclude = datasourceautoconfiguration. Class)

Custom Banner Modify Banner

When we start the Spring boot project, a boot pattern is output by default on the console as follows:

Of course, this pattern can be changed if you need it, and the way to modify it is simple:

1. Create a new Banner.txt document under Src/main/resources
2. Generate the required characters via the HTTP://PATORJK.COM/SOFTWARE/TAAG website and copy the characters to the TXT document created in step 1, for example I'm here for Hello xian! Generate characters, as follows:

Click the Select and Copy button in the lower left corner to copy this character to the TXT document and then start the project, and the text of the console output will automatically change as follows:

Close Banner

Can be modified of course also can be closed, close banner we need to modify the code in the Main method, as follows:

1  Public Static void Main (string[] args) {2         New Springapplicationbuilder (test19springboot2application.  Class); 3         // Modify the banner mode to OFF 4         Builder.bannermode (Banner.Mode.OFF). Run (args); 5     }

OK, so when we start project again, we won't see banner.

Spring Boot configuration file

Spring Boot uses a global configuration file application.properties or APPLICATION.YML, and the configuration file is placed in the Src/main/resources directory. Properties is a common configuration file, Spring boot not only supports the properties of this type of configuration file, but also supports the Yaml language configuration file, here I take the properties type of configuration file as an example to see a few cases.

1. Modify the Tomcat default port and default access path

The Tomcat default port is 8080, I change it to 8081, the default access path is http://localhost:8080, I change it to Http://localhost:8081/helloboot, Let's take a look at how these two requirements are implemented through a simple configuration.
Quite simply, add the following code to the Application.properties file:

server.context-path=/hellobootserver.port=8081

Then start project, which you'll have access to in the browser:

General Property Configuration

In the previous blog (Spring Common configuration) we described how to inject values into the properties file using the Spring container framework. If we were to use spring Boot, it would be easier to do this, we just need to define the attributes in Application.properties and then use @value injection directly in the code.
As follows:

Book.author= Luo guanzhong book.name= kingdoms Book.pinyin=sanguoyanyi

I have a special set of Chinese here, because Chinese do not do special processing will be garbled, the way to continue to add the following code in Application.properties:

1 Server.tomcat.uri-encoding=utf-8 2 Spring.http.encoding.charset=utf-8 3 spring.http.encoding.enabled=true 4 spring.http.encoding.force=true 5 Spring.messages.encoding=utf-8

Then in IntelliJ idea, click File---Settings, Editor---encodings
Set the default encoding for properties files under Properties Files (*.properties) to UTF-8, transparent native-to-ascii Conversion before the check. (Refer to "springboot solution idea Read the Chinese garbled problem of the properties configuration file" "Springboot to solve the idea of reading the properties configuration file in Chinese garbled problem").
It is then injected directly into the variable via @value, as follows:

1  @Value (Value = "${book.author}")2  private  String Bookauthor; 3  @Value ("${book.name}")4  private  String bookname; 5  @Value ("${book.pinyin}")6  private String Bookpinyin;

Modify the index method so that it returns these values:

1 @RequestMapping (value = "/", produces = "Text/plain;charset=utf-8")2    String Index () {3         return "Hello Spring boot! The BookName is "+bookname+", and book Author are "+bookauthor+"; and book PinYin are "+Bookpinyin; 4     }

It is then accessed in the browser with the following results:

Type-Safe configuration

The way we've just said it works a little bit more when we're working on a real project, because there are too many variables to inject in each project, and we can use type-safe configuration in such a way that the Properties property is associated with a bean, which makes it easier to use. Let me see how this works.

1. Create a file under the Src/main/resources folder book.properties

The contents of the file are as follows:

Book.name= Dream Book.author= Cao Xueqin book.price=28

2. Create a book Bean and inject values from the properties file

The code is as follows:

1 @Component2@ConfigurationProperties (prefix = "book", locations = "Classpath:book.properties")3  Public classBookbean {4     PrivateString name;5     PrivateString author;6     PrivateString Price;7 8      PublicString GetName () {9         returnname;Ten     } One  A      Public voidsetName (String name) { -          This. Name =name; -     } the  -      PublicString Getauthor () { -         returnauthor; -     } +  -      Public voidSetauthor (String author) { +          This. Author =author; A     } at  -      PublicString GetPrice () { -         returnPrice ; -     } -  -      Public voidSetprice (String price) { in          This. Price =Price ; -     } to}
This problem occurs with injection:

Prefix refers to the prefix, where the location specifies where to inject the file.

This problem occurs because spring boot1.5 above version @configurationproperties cancels the location annotation.

The following workarounds are recommended for general experience with this issue:

1. The hint that spring boot Configuration Annotation proessor not found in classpath is in use @configurationproperties this annotation, So the problem arises in configurationproperties annotations.
2, according to the hint of not found in Classpath, query the use of this note about how to specify Classpath, and then query location,spring boot1.5 above version @ Configurationproperties Canceling location annotations
3. Solution:

Register as a component with @component in the configuration class, and then use @propertysource to specify a custom resource directory. (I test with @service instead of @component) there are the following three solutions: the first: Create author.properties in Resource and indicate @propertysource (" Author.properties "), that is, by default in resource to find this file, found to return a value, can not find the error, the paper can not be found, can not open.

The second kind: Create Config folder under Resource, put Author.properties under Config, access method is: @PropertySource ("Classpath:config/book.properties" )

The third type: Write directly in application.properties (not recommended, but if the global variable advocates this method), when written in this file, do not need to indicate the resource file path, only need to specify the prefix. As follows:

3. Add a path map

Add the following code to the controller to inject the bean:

@Autowired     Private Bookbean Bookbean;

To add a path map:

@RequestMapping ("/book")    public  String Book () {        return "Hello Spring boot! The BookName is "+bookbean.getname () +", and book Author is "+bookbean.getauthor () +"; Ice ();    }

Add the following code to the controller to inject the bean:

@Autowired     Private Bookbean Bookbean;

To add a path map:

@RequestMapping ("/book")    public  String Book () {        return "Hello Spring boot! The BookName is "+bookbean.getname () +", and book Author is "+bookbean.getauthor () +"; Ice ();    }

The results are as follows:

Log configuration

By default, spring boot uses logback as the log frame, which is the way we used to print the logs in previous blogs, but we can manually configure the log level and log output location if necessary, compared to the log output code we write in the spring container. The configuration here is simply pediatrics, just add the following code to the Application.properties:

logging.file=/home/sang/workspace/log.loglogging.level.org.springframework.web=debug

Above indicates the configuration log output location, below the configuration log level.

Profile configuration Issues

In the spring common configuration article, we've covered the role of profile, how to use the profile in the spring framework, but it was a bit of a hassle for the little ones to see, and the system provided a more concise approach in spring Boot. Global profile Configuration We use application-{profile}.properties to define, The spring.profiles.active is then used in application.properties to specify which profile to use. OK, so let's look at a simple case.

1. Under the Src/main/resources folder, define profile profiles in different environments, The filenames are application-prod.properties and application-dev.properties, which represent the configuration in the production environment, which represents the configuration under the development environment, as follows:

Application-prod.properties:

server.port=8081

Application-dev.properties:

server.port=8080

Then make a simple configuration in Application.properties, as follows:

Spring.profiles.active=dev

This represents the use of the configuration under the development environment. Then we run the project and we have to go through port 8080 to access:

If you want to change into a production environment, you just have to change to spring.profiles.active=dev spring.profiles.active=prod , of course, the access port is also changed to 8081, as follows:

Turn from: 53740047

Springboot Project (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.