Spring——註解篇

Spring:

@Import

  • 簡介:

將資源導入到容器中,實際上是以bean 定義(BeanDeinition)的方式導入到BeanDeinitionMap中

  • 使用介紹

@Import有三種用法

  1. 直接填class數組方式
    @Import({ 類名.class , 類名.class... })
    public class TestDemo {
    
    }
  2. ImportSelector接口(Springboot 自動加載配置類也是使用這個方式
    這種方式的前提就是一個類要實現ImportSelector接口,裏面會有一個需要實現的方法(selectImports),這個方法需要返回字符串數據,Springboot在此讀取了自動配置啓動類中的spring.factories文件,把裏面配置的屬性轉化成字符串數據返回。
    public class Myclass implements ImportSelector {
    //既然是接口肯定要實現這個接口的方法
        @Override
        public String[] selectImports(AnnotationMetadata annotationMetadata) {
            return new String[0];
        }
    }
  3. ImportBeanDefinitionRegistrar (以註冊器的方式)
    同樣是一個接口,類似於第二種ImportSelector用法,相似度80%,只不過這種用法比較自定義化註冊,具體如下:

    public class Myclass2 implements ImportBeanDefinitionRegistrar {
        @Override
        public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
            //指定bean定義信息(包括bean的類型、作用域...)
            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestDemo4.class);
            //註冊一個bean指定bean名字(id)
            beanDefinitionRegistry.registerBeanDefinition("TestDemo4444",rootBeanDefinition);
        }
    }

 

 

@Configuration

  • 簡介:

使被標註的類變成Spring配置類(想學好Spring boot必定需要熟悉此註解,Spring boot大量使用此註解類)

  • 使用介紹

結合@Bean一起使用,把方法中返回的實體類,以方法名作爲key,注入到ioc中

@Scope註解表示bean類的作用域

 可以使用AnnotationConfigApplicationContent來代替ClassPathXmlApplicationContent 來啓動項目

ClassPathXmlApplicationContent的參數是指定配置文件的位置

AnnotationConfigApplicationContent是直接傳入配置類。

@PropertySource

  • 簡介:

加載指定的配置文件到Spring的Environment中,Environment對象只能在初始化時進行調用。

  • 使用介紹

     可以與@Configuration註解搭配使用,在項目初始化階段中把配置環境中的值加載到註冊bean中或配置類中。相比於@ConfigurationProperties這個註解只能用於properties文件。

@Configuration
@PropertySource("classpath:/properties/dev.properties")
public class DriverConfig {

    @Autowired
    Environment environment;

    @Bean
    public Driver testBean() {
        Driver driver = new Driver();
        driver.setName(environment.getProperty("name"));
        driver.setDriver(environment.getProperty("driver"));
        return driver;
    }
}

@Bean

  • 簡介:

@Bean是一個方法級別上的註解,主要用在@Configuration註解的類裏,也可以用在@Component註解的類裏。

  • 使用介紹:

      1、@bean 也可以依賴其他任意數量的bean,如果TransferService 依賴 AccountRepository,我們可以通過方法參數實現這個依賴

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService(AccountRepository accountRepository) {
        return new TransferServiceImpl(accountRepository);
    }
}
  • 屬性   

 initMethod :指定初始化方法

destroyMethod:指定銷燬方法

scope:指定bean的作用域

name:自定義bean名。@Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })還支持別名

@Lazy

  • 簡介
      用於指定該Bean是否取消預初始化。默認爲true,Bean對象在第一次使用時創建。

@ImportResource

  • 簡介:
         Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別,想讓Spring的配置文件生效,加載進來,@ImportResource標註在一個配置類上。

  • 使用介紹:
     @ImportResource(locations = {"applicationContext.xml"}),可以同時加載多個配置文件。
  • 屬性:
       locations 屬性是個數組,可以寫多個文件名。

@Conditional

  • 簡介

    在config類初始化bean時,只有滿足@Conditional條件才能被註冊並放到容器中。
  • 使用介紹
    //此註解可以標註在類和方法上
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME) 
    @Documented
    public @interface Conditional {
        Class<? extends Condition>[] value();
    }
    
    
    //Condition接口
    public interface Condition {
        boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
    }
    @Conditional註解可以指定class數組,實現類要實現Condition接口,實現match方法根據業務邏輯判斷,返回true表示bean可以被註冊,返回false則不被註冊。註解可以用在方法和類上,若指定多個@Condition實現類,要全部爲true時,bean才能被註冊。
  • 屬性:value @Condition實現類數組。

SpringBoot:

@ConfigurationProperties

  • 簡介

    可以直接把寫在配置文件中的數據與類中的屬性相關聯起來。要使用該註解功能的類首要條件要是容器中的組件、可以在類上加上@Component。默認從application.yml或者application.properties文件中獲取屬性。

  • 使用介紹

       與@ConfigurationProperties相似的@Value,也可以結合@propertySource註解,指定要引入的配置文件。

在導入配置文件器後,配置文件進行綁定時就會有提示
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>
  •      屬性

有prefix 屬性,指定爲配置文件哪個屬性下面的所有屬性進行映射。

@ComponentScan

  • 簡介

    掃描同級目錄及以下目錄中所有標識了需要裝配的類自動裝配到spring的bean容器中,默認就會裝配標識了@Controller,@Service,@Repository,@Component等註解。跟xml配置文件中component-scan作用一樣,若Java被上述註解標記了,但沒有被Spring掃描到,這是沒有意義的,並沒有被實例化並加入到容器中。
    <context:component-scan base-package="com.qqa.controller">
            <context:include-filter type="annotation"
                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

     

  • 使用介紹
  • 屬性
    value:指定掃描的目錄
    basePackageClasses:指定具體的掃描的類
    includeFilters:是個過濾器數組可指定多個過濾器
     
    @ComponentScan(value="com.zhang",useDefaultFilters=true,
       includeFilters={
           @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
           @Filter(type=FilterType.ASSIGNABLE_TYPE,classes={UserService2.class})
       })

    excludeFilters:和includeFilters相反,過濾出不加入spring容器的Bean。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章