009.从IoC容器获取Bean

1.从IoC容器获取Bean

 

 2. src/main/java/com/imooc/spring/ioc/SpringApplication.java   

package com.imooc.spring.ioc;


import com.imooc.spring.ioc.entity.Apple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplication
{
    public static void main(String[] args)
    {

        //创建SpringIoc容器,并根据配置文件在容器中实例化
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

        Apple apple4 = context.getBean("apple4", Apple.class);
        System.out.println(apple4.getTitle());

        Apple apple3 =(Apple) context.getBean("apple3");
        System.out.println(apple3.getTitle());

    }
}

3. bean标签中的id和name的区别

 

 

 

 4. 在没有id或者name的bean,默认使用类名全称作为bean的标识

 <!--在没有id或者name的bean,默认使用类名全称作为bean的标识-->
    <bean class="com.imooc.spring.ioc.entity.Apple">
        <constructor-arg name="title" value="红富士3"/>
        <constructor-arg name="color" value="红色"/>
        <constructor-arg name="origin" value="欧洲"/>
        <constructor-arg name="price" value="1145949411.98"/>
    </bean>
   Apple apple = context.getBean("com.imooc.spring.ioc.entity.Apple", Apple.class);
        System.out.println(apple.getTitle());

 

posted @ 2022-11-22 23:42  李林林  阅读(78)  评论(0编辑  收藏  举报