zoukankan      html  css  js  c++  java
  • 016 @Configuration和@Bean

    一. 概述

    @Configuration 注解标记在类上,就像之前我们声明的一个spring的xml配置文件,该类我们称为配置类.

    @Bean 标记在方法之上,方法的返回值为向springIOC容器之中注入一个Bean.

        其中,返回值相当于xml文件bean标签的class属性,方法的名称相当于id属性.

        我们的property属性被放置在了方法的实现之中.

      @Bean注解有一个属性,name属性,可以帮助我们指定Bean的id的名字.


     二 .测试部分

    [1] 创建一个javaBean

    public class Person {
        
        private String name;
        
        private Integer age;

    此处省略getter 和setter方法.

    [2]创建配置类

    @Configuration //相当于xml的spring配置文件
    public class BeanAnnotation {
    
        @Bean //向容器之中注入Bean组件
        public Person person() {
            Person person = new Person();
            person.setName("trek");
            person.setAge(11);
            return person;
        }
    }

    [3]测试类

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=BeanAnnotation.class)
    public class BeanTest {
    
        @Autowired
        private ApplicationContext context ; 
        
        @Test
        public void test1() {
            Person person = context.getBean(Person.class);
            System.out.println(person);
        }
    }

    我们使用spring test完成单元测试功能.


     三 .关于Bean的名字

        @Test
        public void test2() {
            String[] beanDefinitionNames = context.getBeanDefinitionNames();
            for (String name : beanDefinitionNames) {
                System.out.println(name);
            }
        }

    增加测试代码:查看输出---

    beanAnnotation
    person
    我们只看最重要的,person的id为person.现在我们使用@Bean指定Bean的id的名字.

    修改之前的代码:

        @Bean("personName")
        public Person personName() {
            Person person = new Person();
            person.setName("trek");
            person.setAge(11);
            return person;
        }

    在我们的配置类中加入该部分代码.

    再运行上面的测试类:

    结果为:---

    beanAnnotation
    person
    personName

    我们发现有一个Bean的名字变成了personName,说明可以指定Bean的名字.

  • 相关阅读:
    pyqt5 树节点点击实现多窗口切换
    pyglet self.
    itchat key
    python队列Queue
    Python建立多线程任务并获取每个线程返回值
    利用Python实现多线程聊天功能
    Python3.5+PyQt5多线程+itchat实现微信防撤回桌面版代码
    pyglet player sound
    文件打开的几种访问模式
    pyglet StaticSource
  • 原文地址:https://www.cnblogs.com/trekxu/p/9094860.html
Copyright © 2011-2022 走看看