zoukankan      html  css  js  c++  java
  • bean创建

    看《spring源码解析》的笔记

    1、通过@Bean创建bean,类上需要添加@Configuration

    @Configuration
    public class MainConfig {
        
        //给容器中注册一个Bean,类型为返回值的类型。id为默认用方法名作为id
        @Beanpublic Person person01(){
            return new Person("lisi", 20);
        }
    
    }

    2、如果在main函数中,希望查看spring容器添加的Bean

         如果希望可以根据Java类型查看其在容器中的bean名,可以根据getBeanNamesForType函数进行获取。

    public static void main(String[] args) {
            
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
            Person bean = applicationContext.getBean(Person.class);
            System.out.println(bean);
            //根据类型,获取容器中的Bena的名字
            String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
            for (String name : namesForType) {
                System.out.println(name);
            }
        
        }

    3、如果@Bean后没有其他内容,那么bean的名字默认为使用该注解的函数名,如果希望进行制定则:

    @Configuration
    public class MainConfig {
        //给容器中注册一个Bean,类型为返回值的类型。id为默认用方法名作为id
        @Bean("person")
        public Person person01(){
            return new Person("lisi", 20);
        }
    }
  • 相关阅读:
    堆、栈、值类型、引用类型分析总结 Part 2
    DataGridView打印
    学习使用ArrayList
    C#与Java之比较
    【原创】串口通信测试程序
    彩色校验码的制作
    C#中使用进度条
    【原创】 Ajax之ModalPopup编程实例
    常用正则表达式
    堆、栈、值类型、引用类型分析总结 Part 1
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11984906.html
Copyright © 2011-2022 走看看