1. 程式人生 > >spring5.0原始碼筆記

spring5.0原始碼筆記

spring底層主要IOC容器和AOP,IOC底層儲存物件的容器是一個執行緒安全的ConcurrentHashMap容器,即下面這段。

private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);

Configuration註解:

首先來說下xml形式的IOC注入。注意容器的id是不允許重複的,重複啟動會報錯。用@AllArgsConstructor註解的建構函式在xml模式無效,會報錯,需要手寫一個有參建構函式才行。

<bean id="userEntity" class="testspring.UserEntity">
    <property name="name" value="10"/>
    <property name="age" value="haha"/>
</bean>

註解方式注入,可以採用下面方式來注入,預設以方法的名稱為容器id(userEntity)。

//這裡新增的Configuration註解,等同於spring xml檔案配置的IOC
@Configuration
public class MySpringConfig {
    @Bean
    public UserEntity userEntity() {
        return new UserEntity("哈哈", 20);
    }
}

xml和註解方式的注入啟動方式。AnnotationConfigApplicationContext劃重點,面試要問。。。

//定義成全域性的xml檔案方式注入
private static ClassPathXmlApplicationContext applicationContext;
//定義成全域性的註解方式的注入
private static AnnotationConfigApplicationContext annotationConfigApplicationContext;
public static void main(String[] args) {
    //xml檔案方式注入
    applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserEntity userEntity = applicationContext.getBean("userEntity", UserEntity.class);
    System.out.println(userEntity);
    //註解方式注入
    annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MySpringConfig.class);
    UserEntity userEntity1 = annotationConfigApplicationContext.getBean("userEntity", UserEntity.class);
    System.out.println(userEntity1);
}

延申至springboot中的一個註解:@SpringBootConfiguration繼承自@Configuration,二者功能也一致,標註當前類是配置類。因此可以直接在@SpringBootApplication註解的類下直接寫@Bean註解即可注入。

 

ComponentScan註解:

我們在寫三層的時候,比如控制器層的類都新增一個@Controller註解,Service層的類都新增一個@Service註解,資料訪問層都新增一個@Repository註解,那麼這些類怎麼交給spring管理呢,就用到了@ComponentScan註解,定義只要在指定包下面的都會注入到spring容器中去。然後就可以用getBean方法來獲取注入物件的資訊了。

//獲取到所有注入的物件
String[] definitionNames=annotationConfigApplicationContext.getBeanDefinitionNames();

spring中ioc物件預設是單例的,@Scop註解可以指定物件生命週期。

@Scope("singleton")

singleton:全域性有且僅有一個例項,預設的方式。

prototype:每次獲取Bean的時候都會有一個新的例項。

request:表示針對每次請求都會產生一個新的Bean物件,並且該Bean物件僅在當前Http請求內有效。

session:作用域表示每次請求都會產生一個新的Bean物件,並且該Bean僅在當前Http session內有效。

 

 

未完待續。