码迷,mamicode.com
首页 > 移动开发 > 详细

Spring-初始化:AnnotationConfigApplicationContext

时间:2020-04-16 22:26:37      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:domain   tor   pretty   imp   name   上下   app   text   string   

简介

使用AnnotationConfigApplicationContext可以实现基于Java的配置类加载Spring的应用上下文

技术图片

 

 

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

标签:domain   tor   pretty   imp   name   上下   app   text   string   

原文地址:https://www.cnblogs.com/shix0909/p/12716070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!