Spring-初始化(AnnotationConfigApplicationContext)

学向勤中得,萤窗万卷书。这篇文章主要讲述Spring-初始化:AnnotationConfigApplicationContext相关的知识,希望能为你提供帮助。
简介
使用AnnotationConfigApplicationContext可以实现基于java的配置类加载Spring的应用上下文

Spring-初始化(AnnotationConfigApplicationContext)

文章图片

 
 
package com.sixinshuier.springbean.definition; import com.sixinshuier.springbean.Config.BeanConfiguration; import com.sixinshuier.springbean.domain.Toy; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * AnnotationConfigApplicationContext 的使用 */ public class AnntationConfigTest { public static void main(String[] args) { // 创建BeanFactory 容器 AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(); //注册 Configuration Class (配置类) applicationContext.register(BeanConfiguration.class); // 启动Spring应用的上下文 applicationContext.refresh(); // 依赖查找Bean Toy toy1= (Toy) applicationContext.getBean("Toy1"); System.out.println(toy1.getName()+":"+toy1.getSize()); Toy toy2= (Toy) applicationContext.getBean("Toy2"); System.out.println(toy2.getName()+":"+toy2.getSize()); // 关闭spring应用上线文 applicationContext.close(); } }

 
 
package com.sixinshuier.springbean.Config; import com.sixinshuier.springbean.domain.Toy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration //相当于spring xml的< beans> public class BeanConfiguration {@Bean(name = "Toy1")// 相当于< bean> public Toy toy(){ Toy toy=new Toy(); toy.setName("Football"); toy.setSize("big"); return toy; }@Bean(name = "Toy2") public Toy toy1(){ Toy toy=new Toy(); toy.setName("Table tennis"); toy.setSize("small"); return toy; } }

【Spring-初始化(AnnotationConfigApplicationContext)】 

    推荐阅读