spring注解開發AnnotationConfigApplicationContext的使用


https://www.cnblogs.com/kaituorensheng/p/8024199.html

@Configuration可理解為用spring的時候xml里面的<beans>標簽

@Bean可理解為用spring的時候xml里面的<bean>標簽

 

下面是兩種上下文的生成方式,第一種需要執行register,refresh,第二種不需要。原因可以看第三段的源碼,第二種是源碼里面調用了register與refresh。

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();

//////////////////////////////////////
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

////////////////////////////////source code
public AnnotationConfigApplicationContext() {
        this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }

public AnnotationConfigApplicationContext(Class... annotatedClasses) {
        this();
        this.register(annotatedClasses);
        this.refresh();
    }

一種方法用於獲取一個類沒有多個bean的場景,直接通過類名獲取bean

public class JavaConfigTest {
    public static void main(String[] arg) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

        Entitlement ent = ctx.getBean(Entitlement.class);
        System.out.println(ent.getName());
        System.out.println(ent.getTime());
    }
}

 

一種方法用於獲取一個類有多個bean的場景,通過名稱獲取bean

package com.pandx.test.config;

import com.pandx.test.Entitlement;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean(name="entitlement")
    public Entitlement entitlement() {
        Entitlement ent = new Entitlement();
        ent.setName("Entitlement");
        ent.setTime(1);
        return ent;
    }

    @Bean(name="entitlement2")
    public Entitlement entitlement2() {
        Entitlement ent = new Entitlement();
        ent.setName("Entitlement2");
        ent.setTime(2);
        return ent;
    }
}
public class JavaConfigTest {
    public static void main(String[] arg) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);        

        Entitlement ent = (Entitlement)ctx.getBean("entitlement");
        System.out.println(ent.getName());
        System.out.println(ent.getTime());

        Entitlement ent2 = (Entitlement)ctx.getBean("entitlement2");
        System.out.println(ent2.getName());
        System.out.println(ent2.getTime());

        ctx.close();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM