Spring注解系列一:組件注冊-@Configuration和@Bean

轉(zhuǎn):https://blog.csdn.net/lizhiqiang1217/article/details/89890047

1、引入依賴

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>

2、創(chuàng)建類Person

public class Person {

    private String name;
    private Integer age;
    
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    
    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

3、創(chuàng)建配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="person" class="com.atguigu.bean.Person">
        <property name="age" value="18"></property>
        <property name="name" value="zhangsan"></property>
    </bean>
    
</beans>

4、創(chuàng)建測試類

public class MainTest {
    
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        //根據(jù)配置文件獲取applicationContext 
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //根據(jù)bean的名稱獲取組件
        Person bean = (Person) applicationContext.getBean("person");
        System.out.println(bean);
    }
}

5、用配置類代替配置文件

//配置類就相當(dāng)于配置文件
@Configuration  //告訴Spring這是一個配置類
public class MainConfig {
    
    //給容器中注冊一個Bean;類型為返回值的類型,id默認(rèn)是用方法名作為id。也可以在括號內(nèi)指定id
    @Bean("person")
    public Person person01(){
        return new Person("lisi", 20);
    }
}

6、修改測試類

public class MainTest {
    
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        //根據(jù)配置類獲取applicationContext 
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        //根據(jù)bean的類型獲取組件
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
        
        //根據(jù)bean的類型獲取組件名稱
        String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String name : namesForType) {
            System.out.println(name);
        }
    }

}


圖片.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容