Spring Boot Core (basic configuration)

Previous Spring Boot we simply talk about how to quickly create a SpringBoot project. We all know that SpringBoot very powerful and can easily integrate with a variety of tools, but we know these, you must also know why. Today, the beginning and we will study together about SpringBoot core, the core being too important and need to be divided into several chapters, and today we take a look at the basic configuration.

Class inlet and @SpringBootApplication

使用过或者瞄过一眼Spring Boot工程的小伙伴都知道,
SpringBoot有一个特别显著的特点,
就是每个SpringBoot工程都会有一个入口类,
在这个入口类上都会有这么一个注解@SpringBootApplication。

这个类中有一个main方法,main方法中使用
SpringApplication.run(*Application.class,args),
用来启动SpringBoot项目。如下所示:
    public static void main(String[] args) {
        SpringApplication.run(Createproject2Application.class, args);
    }

@SpringBootApplication

@SpringBootApplication是Spring Boot的核心注解,
它是一个组合注解
(通常我们称由多个注解组成的注解叫组合注解)。点进去瞧一眼
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
@SpringBootApplication注解主要(我这里说了主要喔)组合了
@Configuration,@EnableAutoConfiguration,@ComponentScan
言外之意就是可以将这三个注解直接替换@SpringBootApplication

image

  1. Let @EnableAutoCOnfiguration Spring Boot automatically configured according to the class to the current path projects a jar dependent. Such as adding a spring-boot-starter-web-dependent, automatically added dependence Tomcat and Spring MVC, Spring Boot for Tomcat and Spring MVC will be automatically configured.

2. @ ComponentScan let Spring Boot to scan and import category at the same level and Bean less bag (using annotations configuration), add them to the Spring container, for the JPA entity class if the project can also scan the label @Entity.

3. @ Configuration indicates that the current configuration is a class, it will be Spring loaded

Close particular autoconfiguration

SpringBoot为我们提供了自动化配置,但是在某些特定的场景下,
我们可能不需要某个自动配置,
这时可以在@SpringBootApplication中配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

Custom Banner

什么是Banner呢,
就是在Spring Boot项目启动的时候最开始显示的横幅。
我记得我第一次启动Spring Boot项目的时候印象最深的就是这个横幅
内心不断OS(wc这么酷炫的吗)。

下面我们看看怎么自定义横幅吧。如果不自定义,默认显示下面图案

image

Modify Banner

  1. We create a new banner.txt in src / main / sources
  2. Login http://patorjk.com/software/taag generate our own desired pattern
    image
  3. Copying the pattern to banner.txt
    image
  4. Start project verification
    image

Close banner

当然了,这个banner也不是必须要显示的,我们可以手动关闭它。
  • 修改启动类中的main方法
  SpringApplication app = new SpringApplication(Createproject2Application.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

Spring Boot's profile

Spring Boot在src/main/resources下有一个全局的配置文件
application.properties或application.yml

说到yml这种配置文件,是有点东西的。全称为yaml,是以数据为中心,
支持多种数据格式(如数组),在配置数据的时候具有面向对象的特征。

A simple example

在两种配置文件中配置Tomcat的端口号和默认的访问路径
  • application.properties may be configured as follows:
server.port=8888
server.servlet.context-path=/xicent
  • application.yml may be configured as follows:
server:
  port: 8888
  servlet:
    context-path: /xicent

In fact, we can see from simple examples, yaml format more clearly, all configuration glance at the past. And it is ordered.
Before the idea is not supported yml prompt, and now also supported.
But yaml has led to another problem, there are strict requirements yaml format, with a little wrong there are problems that may arise.
Therefore, the project seen us how to choose the current or in default properties based.

Use the xml configuration

Spring Boot提倡的是0配置,即无xml配置,但是在实际开发中,
我们有时难免会需要加载xml配置,
这时我们就可以通过Spring提供的@ImportResource来加载xml配置
例如:
@ImportResource({"classpath:some-context.xml"})
这样我们就成功加载xml配置啦。

Command line parameters

在Spring Boot中,我们大部分配置都写在了配置文件中,
但是有些配置我们可能需要启动时才能确定,
因此Spring Boot还提供了一种命令行配置方式
下面演示如何在运行jar包的时候,配置Tomcat的端口号
    java -jar xx.jar --server.port=8888

Configuring General Properties

在常规的Spring环境中,如果我们想加载某个properties文件,
获取其中的配置。通常的做法是在类上加注解@PropertiesSource()
指定配置文件的位置。
然后在类中使用@Value()加载属性。

在Spring Boot中,
我们只需在application.properties中定义属性,
直接用@Value注入即可。

1.application.properties increase property

xicent.author=kris
xicent.age=1

2. Modify the entry class

@Value("${xicent.author}")
String name;

@Value("${xicent.age}")
int age;

@RequestMapping("/")
String index(){
    return "author is"+name+",age is"+age;
}

Other property acquisition

通用我们用@Value都是获取properties配置文件中配置的属性,
但是@Value的功能可不远远不止这一点喔。
通过@Value注解,
我们还能获取系统属性,url,随机数,文字流等等。
//  普通字符串
    @Value("xicent")
    private String str;

//  操作系统名称
    @Value("#{systemProperties['os.name']}")
    private String osName;

//    随机数
    @Value("#{T(java.lang.Math).random()*168.0}")
    private double randomNumber;

//  其他bean的属性
    @Value("#{demoService.another}")
    private String fromAnother;

//  获取文件资源
    @Value("classpath:banner.txt")
    private Resource file;

//   获取地址资源
    @Value("http://www.baidu.com")
    private Resource url;

    public void testValue() throws IOException {
        System.out.println(getStr());
        System.out.println(getOsName());
        System.out.println(getRandomNumber());
        System.out.println(getFromAnother());
        System.out.println(IOUtils.toString(file.getInputStream(),"UTF-8"));
        System.out.println(IOUtils.toString(url.getInputStream()));
    }

//省略getter,setter方法

Access Interface

    @RequestMapping("/testvalue")
    void testValue() throws IOException {
        xicentBean.testValue();
    }

image

Type secure configuration (based on properties)

上面的例子,我们每个属性都要使用@Value注解会显得格外的麻烦,
我们配置的属性通常会是许多个。
在Spring Boot中使用@ConfigurationProperties
将配置与bean相关联,
这就是所谓的类型安全的配置。

这里将配置配在一个专门的properties文件中,
当然也能直接配置在application.properties中

1.resources folder xicent.properties new file, add the following attributes

xicent.author=kris
xicent.age=1

2. Create a class

@Component
@PropertySource("classpath:xicent.properties")
@ConfigurationProperties(prefix = "xicent")
public class XicentBean {
    private String author;
    private int age;

Code explanation: @PropertySource can specify the path to the file we want to load. @ConfigurationProperties specify a prefix we attribute configuration

3. Create access interfaces

    @Autowired
    XicentBean xicentBean;

    @RequestMapping("/xicent")
    XicentBean getXicent(){
        return xicentBean;
    }

4. Request Interface

image

Profile Configuration

Profile是Spring用来针对不同环境使用不同的配置文件。
一般命名为:application-{profile}.properties
(如application-prod.properties)。

然后在application.properties中
设置spring.profiles.active=prod来指定活动的Profile。
下面演示生产环境(prod)使用8888端口,
开发环境(dev)使用9999端口

1. Create application-prod.properties, port configuration of the production environment

server.port=8888

2. Create application-dev.properties, port configuration development environment

server.port=9999

3.application.properties specified in effect profile

spring.profiles.active=prod

image

4. Start project, you can see the prod profile entry into force, bind to port 8888

image

Question: If I application.properties and application-prod.properties are equipped with a port, which will take effect then? The answer is prod takes effect

ok, so much more attractive today temporarily share, more than talking about the Spring Boot in basic configuration, in which there are many places you can dig deep to come up with in terms of the individual.
Today, where we talk about some basic, commonly used basic configuration, and then we will follow in detail to share.

Like small number of public partners can focus on: good news XiCent have any questions, feel free to ask me oh ~

Guess you like

Origin www.cnblogs.com/xicent/p/11570535.html