Spring的getBean()方法

xml配置


    
    

    

    
    
    

    
    

java调用

package com.sy.Demo1.text;

import com.sy.Demo1.dao.SpringDao;
import com.sy.Demo1.dao.impl.SpringDaoImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;

public class Text {
    public static void main(String[] args) {
//        实例对象
        SpringDao springDao0 = new SpringDaoImpl();
//        getBean获取对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(ac);
        SpringDao springDao = (SpringDao) ac.getBean("springDao");
        System.out.println(springDao);
        SpringDao springDao1 = (SpringDao) ac.getBean("springDao");
        System.out.println(springDao1);
//        SpringDao springDao2=ac.getBean(SpringDao.class);
//        System.out.println(springDao2);
        SpringDao springDao3 = ac.getBean("springDao", SpringDao.class);
        System.out.println(springDao3);
        SpringDao springDao4 = ac.getBean("springDao2", SpringDao.class);
        System.out.println(springDao4);
        String[] beanNames = ac.getBeanDefinitionNames();
        System.out.println(Arrays.toString(beanNames));
        SpringDao springDao2 = ac.getBean(beanNames[0], SpringDao.class);
        System.out.println(springDao2);

    }
}

输出结果

无参构造方法
无参构造方法
org.springframework.context.support.ClassPathXmlApplicationContext@17f052a3: startup date [Mon Jun 24 16:55:19 CST 2019]; root of context hierarchy
com.sy.Demo1.dao.impl.SpringDaoImpl@204f30ec
com.sy.Demo1.dao.impl.SpringDaoImpl@204f30ec
com.sy.Demo1.dao.impl.SpringDaoImpl@204f30ec
com.sy.Demo1.dao.impl.SpringDaoImpl@e25b2fe
[springDao, springDao2]
com.sy.Demo1.dao.impl.SpringDaoImpl@204f30ec

你可能感兴趣的:(框架)