beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!--告诉spring创建对象
  6. 声明bean,就是告诉spring要创建某个类的对象
  7. id:对象的自定义名称,唯一值。spring通过这个名称找到对象
  8. class: 类的全限定名称(不是接口,因为spring是反射机制,反射机制创建对象,必须使用类)
  9. spring就完成 SomeService someService = new SomeServiceImpl();
  10. spring把创建好的对象放入了map中,spring框架中会有一个map存放对象的。
  11. springMap.put(id的值,对象);
  12. 例如: springMap.put("someService",new SomeServiceImpl());
  13. 一个bean标签声明一个对象
  14. -->
  15. <bean id="someService" class="org.chentianyu.impl.SomeServiceImpl" />
  16. <bean id="someService1" class="org.chentianyu.impl.SomeServiceImpl" />
  17. </beans>

提供容器中提供对象的数量:getBeanDefinitionCount()

@Test
public void test03(){
    String config = "beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
    //使用spring提供的方法,获取容器中提供对象的数量
    int num = applicationContext.getBeanDefinitionCount();
    System.out.println("容器中定义对象的数量:" + num);
}
容器中定义对象的数量:2

容器中每个定义的对象的名称

@Test
public void test03(){
    String config = "beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
    String[] names = applicationContext.getBeanDefinitionNames();
    for (String name: names){
        System.out.println(name);
    }
}
someService
someService1

创建非自定义对象

<?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">
    <!--告诉spring创建对象
    声明bean,就是告诉spring要创建某个类的对象
    id:对象的自定义名称,唯一值。spring通过这个名称找到对象
    class: 类的全限定名称(不是接口,因为spring是反射机制,反射机制创建对象,必须使用类)
    spring就完成 SomeService someService = new SomeServiceImpl();
    spring把创建好的对象放入了map中,spring框架中会有一个map存放对象的。
    springMap.put(id的值,对象);
    例如:  springMap.put("someService",new SomeServiceImpl());

    一个bean标签声明一个对象
    -->
    <bean id="someService" class="org.chentianyu.impl.SomeServiceImpl" />
    <bean id="someService1" class="org.chentianyu.impl.SomeServiceImpl" />
    <!--
        spring能创建一个非自定义的对象吗?创建一个存在的某个类的对象。
    -->
    <bean id="myDate" class="java.util.Date" />
</beans>
@Test
public void test04(){
    String config = "beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
    //使用getBean
    Date my = (Date)applicationContext.getBean("myDate");
    System.out.println("Date:" + my);
}
Date:Tue Apr 05 09:11:03 CST 2022

所以Spring能创建自定义的对象不是自定义的对象,调用的是无参构造方法