Spring注解系列一:组件注册-@Configuration和@Bean

转: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、创建类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、创建配置文件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、创建测试类

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

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

//配置类就相当于配置文件
@Configuration  //告诉Spring这是一个配置类
public class MainConfig {
    
    //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id。也可以在括号内指定id
    @Bean("person")
    public Person person01(){
        return new Person("lisi", 20);
    }
}

6、修改测试类

public class MainTest {
    
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        //根据配置类获取applicationContext 
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        //根据bean的类型获取组件
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
        
        //根据bean的类型获取组件名称
        String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String name : namesForType) {
            System.out.println(name);
        }
    }

}


图片.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容