【Spring】Bean对象和SpringBoot原理

Bean的管理

获取bean对象

默认情况下Spring项目启动的时候,会把bean都创建好放到IOC容器当中,Spring也提供了一些方法来让我们获取到bean对象

// 根据name获取bean
Object getBean(String name)
// 根据类型获取brean
<T> T getBean(Class<T> requiredType)
// 根据name获取bean(带类型转换)
<T>T getBean(String name,Class<T> requiredType)

例子

package com.itheima;
import com.itheima.controller.DeptController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
class SpringbootAllPra002ApplicationTests {
   

    @Autowired
    private ApplicationContext context; // ioc容器对象

    @Test
    public void testGetBean(){
   
        DeptController deptController = context.getBean(DeptController.class);
        System.out.println(deptController);
        DeptController deptController1 = context.getBean("deptController", DeptController.class);
        System.out.println(deptController1);
        DeptController deptController2 = (DeptController) context.getBean("deptController");
        System.out.println(deptController2);
    }

}

com.itheima.controller.DeptController@21a0795f
com.itheima.controller.DeptController@21a0795f
com.itheima.controller.DeptController

你可能感兴趣的:(Spring,spring,spring,boot,java)