SpringBoot(二):SpringBoot常用注解介绍

@SpringBootApplication

package com.lpl.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

@SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解:
这里写图片描述
该注解主要组合了以下注解:

@SpringBootConfiguration:

这是Spring Boot项目的配置注解,这也是一个组合注解,它包含了@Configuration注解,在Spring Boot项目中推荐使用@ SpringBootConfiguration替代@Configuration
这里写图片描述

@Configuration

提到@Configuration就要提到他的搭档@Bean。SpringBoot提倡基于java的配置,使用这两个注解就可以创建一个简单的spring配置类,@Configuration可以用来替代相应的xml配置文件。可以说就是替代原来的xml文件。@Bean就是xml中的每一个bean。

@EnableAutoConfiguration:

启用自动配置,该注解会使Spring Boot根据项目中依赖的jar包自动配置项目的配置项:
如:我们添加了spring-boot-starter-web的依赖,项目中也就会引入SpringMVC的依赖,Spring Boot就会自动配置tomcat和SpringMVC
这里写图片描述
如果我们不需要Spring Boot自动配置,想关闭某一项的自动配置,该如何设置呢?
比如:我们不想自动配置Redis,想手动配置,就可以使用以下注解进行关闭
这里写图片描述

@ComponentScan

默认扫描@SpringBootApplication所在类的同级目录以及它的子目录
所以我们的启动类一般放在项目包的根目录,这样就能扫描到所有包下的配置

@ImportRecourse

SpringBoot提倡零配置,即无xml配置,但是在实际项目中,可能有一些特殊要求你必须使用xml文件,这时候我们可以用@ImportRecourse注解来加载xml的配置文件。
如:@ImportRecourse({“classpath:config/mybatis.xml,confco/test.xml”}) 来加载mybatis的一些配置。

@PropertySource

@PropertySource用来加载properies文件。

@Value

加载properties文件中的value值

@Configuration
@PropertySource("classpath:config/redis.properties")
public class RedisConfig {

    @Value("${redis.hostName}")
    private String hostName;

    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.password}")
    private String password;

    @Value("${redis.sentinel.host1}")
    private String senHost1;

    @Value("${redis.sentinel.port1}")
    private Integer senPort1;

猜你喜欢

转载自blog.csdn.net/plei_yue/article/details/78978727