Spring註解開發

系統常用的三種ApplicationContext:

ClassPathXmlApplicationContext:從類路徑中加載配置文件初始化上下文

FileSystemApplicationContext:從文件系統中加載配置文件初始化上下文

AnnotationConfigApplicationContext:通過註解配置初始化上下文

WebApplicationContext:web應用的上下文

常用註解:

@Component:常用於組件註冊

@Repository:常用於DAO層註冊

@Service:常用於業務接口實現類註冊

@Configuration:配置類,相當於一個配置文件,作用於類上面

@Controller:常用於解析請求

@RestController:同上,該註解下的方法全部返回數據

@RequestMapping:請求映射路徑

@GetMapping:get請求映射

@PostMapping:post請求映射

@RequestBody:獲得post請求body的內容

@ResponseBody:將返回json響應內容

高級註解:

@ComponentScan:配置要掃描的包。作用於類上面。

@ComponentScans:相當於指定多個@ComponentScan

@Scope:指定實例的生成規則,默認爲單實例

@Import:快速給容器導入組件(ImportSelector:導入選擇器,id默認是全類名,作爲@Import的值使用)

@PostConstruct:類初始化的時候調用

@PreDestroy:類銷燬的時候調用

@Conditional:按條件註冊實例或者配置管理類。value值爲實現Condition的類  

@ComponentScan使用詳解:

basePackages和value作用相等,表示要掃描的包及其該包下面的子包

useDefaultFilters:是否使用默認的掃描過濾器,默認爲true

lazyInit:是否使用懶加載機制,默認爲false

excludeFilters:指明要被排除的註解的規則,當useDefaultFilters爲true的時候配合使用。

includeFilters:指明要被掃描的註解的規則,當useDefaultFilters爲false的時候配合使用。

FilterType:ANNOTATION(按註解進行掃描),ASSIGNABLE_TYPE(按指定的類型進行掃描),

	ASSIGNABLE_TYPE(使用ASPECTJ表達式,不經常使用),REGEX(按正則表達式進行掃描),
	
	CUSTOM(自定義規則,該規則需要實現TypeFilter接口)
public class CustomeTypeFilter implements TypeFilter {

    /**

     *

     * @param metadataReader 讀取正在掃描的類的信息

     * @param metadataReaderFactory 讀取其他任何類的信息

     * @return

     * @throws IOException

     */

    @Override

    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {

        //獲取當前類的註解信息

        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

        //獲取當前類的類信息

        ClassMetadata classMetadata = metadataReader.getClassMetadata();

        String className = classMetadata.getClassName();

        //獲取當前類的資源信息

        Resource resource = metadataReader.getResource();

        if(className.contains("er")){

            return true;

        }

        return false;

    }

}

@Scope詳解:

value值:

singleton:單實例,等同於ConfigurableBeanFactory#SCOPE_SINGLETON

prototype:多實例,等同於ConfigurableBeanFactory#SCOPE_PROTOTYPE

request:每次請求產生一個實例,等同於org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST

session:每個會話產生一個實例,等同於org.springframework.web.context.WebApplicationContext#SCOPE_SESSION

globalSession:全局會話產生一個實例,等同於org.springframework.web.context.WebApplicationContext#SCOPE_GLOBAL_SESSION //全局會話產生一個實例

@Conditional詳解:

public class WindowCondition implements Condition {

 

    /**

     *

     * @param conditionContext 判斷條件能使用的上下文環境

     * @param annotatedTypeMetadata 註釋信息

     * @return

     */

    @Override

    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {

        //獲取ioc當前的類工廠

        ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();

        //獲取類加載器

        ClassLoader contextClassLoader = conditionContext.getClassLoader();

        //獲取系統環境變量

        Environment environment = conditionContext.getEnvironment();

        //獲取bean定義的註冊類

        BeanDefinitionRegistry registry = conditionContext.getRegistry();

        //獲取資源加載器

        ResourceLoader resourceLoader = conditionContext.getResourceLoader();

 

        if(registry.containsBeanDefinition("person") && environment.getProperty("os.name").toLowerCase().contains("window")){

            return true;

        }

        return false;

    }

}

@Configuration
public class SpringConfig {

	@Conditional(value = {WindowCondition.class})
    @Bean
    public Person person01() {
        return new Person("bill", 60);
    }

}

@Import詳解:

/**
 * ImportSelector:導入選擇器,id默認是全類名,作爲@Import的值使用。
 */
public class MyImportSelector implements ImportSelector {

    @Override

    public String[] selectImports(AnnotationMetadata annotationMetadata) {

        return new String[]{"com.wyn.bean.Red"};

    }

}

/**
 * ImportBeanDefinationRegister:導入bean定義註冊器,作爲@Import的值使用。
 */
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

        boolean green = beanDefinitionRegistry.containsBeanDefinition("com.wyn.bean.Green");

        boolean red = beanDefinitionRegistry.containsBeanDefinition("red");

        if(green && red){

            RootBeanDefinition rainBow = new RootBeanDefinition(RainBow.class);

            rainBow.setScope(RootBeanDefinition.SCOPE_SINGLETON);

            rainBow.setLazyInit(true);

            beanDefinitionRegistry.registerBeanDefinition("rainBow", rainBow);

        }

    }

}

@Import(value = {Green.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class SpringConfig {

}

更多問題可以加微信公衆號:代碼小棧,期待爲您解決更多問題
代碼小棧

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