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

上一篇:手机连接fiddler无法上网


下一篇:axios post 请求传递参数格式为 key : value