Spring Boot 注解类


一:Springboot 核心注解:

  @SpringBootApplication 是springboot的核心注解,目的是开启自动配置。


  @SpringBootApplication注解组合了@Configuration、@EnablAutoConfiguration 、@ComponentStan。这个三个注解和@SpringBootApplication是互为替代关系;


  @EnableAutoConfiguration作用是让SpringBoot根据类路径中的jar包依赖为当前项目进行自动配置;@Configuration 声明当前类位配置类(xml)


  @ComponentStan自动扫描包,扫描改层下所有声明bean的注解类,并且向spring容器中注册为bean;一般为@ComponentSatn("包路径")。


二:关闭特定的自动配置:
   在springboot中所有的配置都是有默认值的,但是如果要关闭特定的配置,就需要用到@SpringBootApplication中的exclude参数,比如:@SpringBootapplication(exclude={DataSourcAutoConfiguration.class})。


三:配置特定的xml
   在Springboot中可以通过注解@Configuration和@Bean实现无xml配置的效果,但是如果必须要用到xml,可以通过Spring提供的@ImportResource来加载xml,例如:
@ImportResource({"classpath:some-context.xml","classpath:another-context.xml"})




四:配置properties文件
  在spring 环境下可以通过@PropertySource("classpath:com/****/**.properties")获取**.properties文件;
通过@Value在类中注入值;
例如:
**.properties文件如下:
Book.author=mengdonghui
Book.name=spring boot


在class Elconfig中使用:
@Configuration
@ComponentScan("//***///"层)
@PropertySource("classpath:com/****/**.properties")
Public class ElConfig{


  @Value("www.baidu")//为url直接赋值为www.baidu
  Private String url;


  @Value("${book.name}")//为bookname直接赋值为.properties文件中的Book.name=spring boot
  private String bookname;}



Ps:在Spring中时需要用到@PropertySource来引入,而在Springboot中,直接用@Value(“${}”)就可以了;


  使用@Value注入properties中的属性,在配置文件多时,会需要注入多次,会很麻烦。Spring boot 还提供了一种基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全的配置。
******在application.properties中添加属性******
Author.name=mdh
Author.sex=man
**********************************************


代码类:
**********************************************
@Component
@ConfigurationProperties(prefix="author")//通过prefix属性指定properteis的配置前缀;
Public class AuthorSettings{


      private String name;
      private String sex;


      public String getName(){


        return name;
       }


      public String setName(String name){
 
        // 这里的name 是properties文件中atuthor的name值;
        this.name=name;
       }


}
**********************************************


   如果不在application.properties中添加,而是新建一个.properties文件的话,需要使用@ConfigurationProperties的属性locations里指定properties的位置,且需要在入口类中配置。
*****************************************************************************************
@ConfigurationProperteis(prefix="author",location={"classpath:config/author.properties"})
****************************************************************************************


五:外部配置:
  Springboot 使用一个全局的配置文件application.properties 或application.yaml,位置在src/main/resources.Spring boot 的全局配置文件的作用是对一些默认配置的呃配置值进行修改;


例如在application.properties中配置:
Server.port=9089
Server.context-path=/helloboot

或者在application.yaml中配置
Server:
    port:9089
    context-path=/helloboot


评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值