Spring 获取bean的两种实现方式

一、准备工作

1、需要导入spring-context依赖

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

2、创建实体类Person

public class Person {

    private int age;
    private String name;

    public Person() {

    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
    
}

二、通过xml获取bean

1、创建beans.xml用来配置bean

<?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="Person">
        <property name="age" value="20"/>
        <property name="name" value="zhangsan"/>
    </bean>

</beans>

2、main方法调用测试方法

public static void main(String[] args) {
    testXml();
}

public static void testXml(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Person person = (Person) context.getBean("person");
    System.out.println(person);
}

三、通过注解获取bean

1、创建BeansConfig配置类,用来配置bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeansConfig {

    @Bean
    public Person person(){
        return new Person(20,"zhangsan");
    }

}

2、main方法调用测试方法

public static void main(String[] args) {
    testAnnotation();
}

public static void testAnnotation(){
    ApplicationContext context = new AnnotationConfigApplicationContext(BeansConfig.class);
    Person person = (Person) context.getBean("person");
    System.out.println(person);
}

四、总结分析

本章主要学习了,spring通过xml或注解获取bean的两种方式。《参考资料》

猜你喜欢

转载自blog.csdn.net/weixin_40968009/article/details/129752477
今日推荐