Spring注解驅(qū)動開發(fā)(三)

https://github.com/cuzz1/learn-demo/tree/master/demo-05-spring-annotation

1. 屬性賦值@value賦值

使用@Value賦值

  • 基本數(shù)值
  • 可以寫SPEL表達式 #{}
  • 可以${}獲取配置文件信息(在運行的環(huán)境變量中的值)

使用xml時候?qū)肱渲梦募?/p>

<context:property-placeholder location="classpath:person.properties"/>

使用注解可以在配置類添加一個@PropertySource注解把配置文件中k/v保存到運行的環(huán)境中

使用${key}來獲取

/**
 * @Author: cuzz
 * @Date: 2018/9/24 18:43
 * @Description:
 */
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValue {

    @Bean
    public Person person() {
        return new Person();
    }
}
@Data
public class Person {

    @Value("vhuj")
    private String name;

    @Value("#{20-2}")
    private Integer age;

    @Value("${person.nickName}")
    private String nickName;
}

測試

    @Test
    public void test01() {
        printBean(applicationContext);
        System.out.println("---------------------------");

        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);

        System.out.println("---------------------------");

    }

輸出

---------------------------
Person(name=vhuj, age=18, nickName=三三)
---------------------------

2. 自動裝配@Autowired@Qualifier@Primary

自動轉(zhuǎn)配:

? Spring利用依賴注入(DI),完成對IOC容器中各個組件的依賴關系賦值

@Autowired自動注入:

? a. 默認優(yōu)先按照類型去容器中尋找對應的組件,如果找到去賦值

? b. 如果找到到相同類型的組件,再將屬性名(BookDao bookdao)作為組件的id去容器中查找

? c. 接下來還可以使用@Qualifier("bookdao")明確指定需要裝配的id

? d. 默認是必須的,我們可以指定 @Autowired(required=false),指定非必須

@Primary讓Spring自動裝配時首先裝配

3. 自動裝配@Resource和@Inject

Spring還支持使用@Resource (JSR250) 和@Inject (JSR330) 注解,這兩個是java規(guī)范

@Resource和@Autowired一樣實現(xiàn)自動裝配功能,默認是按組件名稱進行裝配的

沒有支持@Primary和@Autowird(required=false)的功能

4. 自動裝配其他地方的自動裝配

@Autowired:構(gòu)造器、參數(shù)、方法屬性等

標注到方法位子上@Bean+方法參數(shù),參數(shù)從容器中獲取

/**
 * @Author: cuzz
 * @Date: 2018/9/24 20:57
 * @Description:
 */
public class Boss {
    // 屬性
    @Autowired
    private Car car;
    
    // 構(gòu)造器 如果構(gòu)造器只有一個有參構(gòu)造器可以省略
    @Autowired
    public Boss(@Autowired ar car) {
    }

    public Car getCar() {
        return car;
    }
    
    // set方法
    @Autowired       // 參數(shù)
    public void setCar(@Autowired Car car) {
        this.car = car;
    }
}

5. 自動裝配Aware注入Spring底層注解

自定義組件想要使用Spring容器底層的一些組件(ApplicationContext,BeanFactory 等等),自定義組件實現(xiàn)xxxAware,在創(chuàng)建對象的時候會調(diào)用接口規(guī)定的方法注入相關的組件

/**
 * Marker superinterface indicating that a bean is eligible to be
 * notified by the Spring container of a particular framework object
 * through a callback-style method. Actual method signature is
 * determined by individual subinterfaces, but should typically
 * consist of just one void-returning method that accepts a single
 * argument.
 */
public interface Aware {

}

我們實現(xiàn)幾個常見的Aware接口

/**
 * @Author: cuzz
 * @Date: 2018/9/25 10:18
 * @Description:
 */
@Component
public class Red implements BeanNameAware ,BeanFactoryAware, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setBeanName(String name) {
        System.out.println("當前Bean的名字: " + name);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("當前的BeanFactory: " + beanFactory);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        System.out.println("傳入的ioc: " + applicationContext);
    }
}

注入到配置中測試

/**
 * @Author: cuzz
 * @Date: 2018/9/25 10:28
 * @Description:
 */
public class IOCTestAware {

    @Test
    public void test01() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAware.class);

    }
}

測試結(jié)果

當前Bean的名字: red
當前的BeanFactory: org.springframework.beans.factory.support.DefaultListableBeanFactory@159c4b8: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,mainConfigOfAware,red]; root of factory hierarchy
傳入的ioc: org.springframework.context.annotation.AnnotationConfigApplicationContext@1e89d68: startup date [Tue Sep 25 10:29:17 CST 2018]; root of context hierarchy

把Spring自定義組件注入到容器中

原理:

public interface ApplicationContextAware extends Aware {}

xxxAware都是通過xxxProcessor來處理的

比如:ApplicationContextAware 對應ApplicationContextAwareProcessor

6. 自動裝配@Profile環(huán)境搭建

Profile是Spring為我們提供可以根據(jù)當前環(huán)境,動態(tài)的激活和切換一系組件的功能

a. 使用命令動態(tài)參數(shù)激活:虛擬機參數(shù)位子加載 `-Dspring.profiles.active=test

b. 使用代碼激活環(huán)境

/**
 * @Author: cuzz
 * @Date: 2018/9/25 10:59
 * @Description:
 */
public class IOCTestProfile {

    @Test
    public void test01() {
        // 1. 使用無參構(gòu)造器創(chuàng)建一個applicationContext
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2. 設置要激活的環(huán)境
        applicationContext.getEnvironment().setActiveProfiles("test");
        // 3. 注冊主配置類
        applicationContext.register(MainConfigOfProfile.class);
        // 4. 啟動刷新容器
        applicationContext.refresh();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 1.1 spring IoC容器和beans的簡介 Spring 框架的最核心基礎的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,851評論 2 22
  • 1.1 Spring IoC容器和bean簡介 本章介紹了Spring Framework實現(xiàn)的控制反轉(zhuǎn)(IoC)...
    起名真是難閱讀 2,672評論 0 8
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • 我只是一個囚徒 可我心里依然懷揣著滾燙的愛 這份愛就像一個火球 在我的胸膛里熊熊燃燒 我的愛要燒光這監(jiān)獄的銅墻鐵壁...
    上官飛鴻閱讀 332評論 11 10

友情鏈接更多精彩內(nèi)容