001 @Configuration and @Bean annotations

I. Overview

The @Configuration annotation is marked on the class, just like a spring xml configuration file we declared before, this class is called the configuration class.

@Bean is marked on the method, and the return value of the method is to inject a Bean into the springIOC container.

    Among them, the return value is equivalent to the class attribute of the bean tag of the xml file, and the name of the method is equivalent to the id attribute.

    Our property attribute is placed inside the method implementation.

  The @Bean annotation has an attribute, the name attribute, that can help us specify the name of the bean's id.

 


 

2. Test part

[1] Create a javaBean

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

The getter and setter methods are omitted here.

[2] Create a configuration class

@Configuration // Spring configuration file equivalent to xml 
public  class BeanAnnotation {

    @Bean // Inject the Bean component into the container 
    public Person person() {
        Person person = new Person();
        person.setName("trek");
        person.setAge(11);
        return person;
    }
}

[3] Test class

@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);
    }
}

We use spring test to complete the unit test function.


 

3. About the name of Bean

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

Add test code: view output---

beanAnnotation
Person We only look at the most important, the person 
's id is person. Now we use @Bean to specify the name of the bean's id.

Modify the previous code:

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

Add this part of the code to our configuration class.

Then run the above test class:

The result is:---

beanAnnotation
person
personName

We found that the name of a bean has become personName, indicating that the name of the bean can be specified.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324551894&siteId=291194637