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的名字.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM