springboot常用注解

1.@SpringBootApplication

等价于 @Configuration @EnableAutoConfiguration @ComponentScan,用此注解标注的类,是springboot应用的入口类

2.@Configuration

这里的@Configuration对我们来说不陌生,它就是JavaConfig形式的Spring Ioc容器的配置类使用的那个@Configuration,SpringBoot社区推荐使用基于JavaConfig的配置形式,所以,这里的启动类标注了@Configuration之后,本身其实也是一个IoC容器的配置类。

相当于xml配置的<beans></beans>标签。

另外,你也可以使用 @ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。因为从@Configuration注解定义中可以看到,它也是一个@Component,因此它可以被@ComponentScan自动搜集到。

3.@EnableAutoConfiguration

第二类级别的注解@EnableAutoConfiguration。这个注解告诉Spring Boot根据添加的jar依赖猜想你如何配置Spring。

由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。Starter POMs和Auto-Configuration:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。

你可以通过将 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一个 @Configuration 类上来选择自动配置。
注:你只需要添加一个 @EnableAutoConfiguration 注解。我们建议你将它添加到主 @Configuration 类上。

如果发现应用了你不想要的特定自动配置类,你可以使用 @EnableAutoConfiguration 注解的排除属性来禁用它们。

复制代码
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

4.@ComponentScan

相当于xml的<context:componentscan basepackage="">

我们经常使用 @ComponentScan 注解搜索beans,你的所有应用程序组件( @Component , @Service , @Repository , @Controller 等)将被自动注册为Spring Beans。

5.@RestController和@RequestMapping注解

@RestController 和 @RequestMapping 注解是Spring MVC注解(它们不是Spring Boot的特定部分)

@RestController是@Controller与@ResponseBody的合集

6.@ConfigurationProperties

当我们有很多配置属性的时候,我们可以把这些属性当作字段建立一个bean,并将属性值赋予它们。

在application.properties配置属性

instance.ip=192.168.1.111
instance.port=8090

@ConfigurationProperties(prefix="instance")
public class ServerBean {

    private String ip;
    
    private String port;

        .....
}

这样就把配置文件中的属性一一映射到了bean中,那么如何把配置文件属性注入到bean中呢?

是@EnableConfigurationProperties

7.@EnableConfigurationProperties

在应用主类application中加上@EnableConfigurationProperties({ServerBean.class}),作用?

一般@ConfigurationProperties和@EnableConfigurationProperties结合使用

 

原文地址:https://www.cnblogs.com/whx7762/p/7832887.html