SpringIOC容器的两种形式

SpringIOC容器的两种形式:

    1.xml配置文件:
            applicationContext.xml

    2.注解形式:
           带有@Configuration注解的类(配置类:相当于applicationContext.xml)

    注:两种形式获取的IOC容器是独立的。

IOC容器的功能:

            1.存bean
                    a.xml配置文件形式:
                        <bean id="" class=""></bean>

                    b.配置类的形式:
                        方法上加@Bean注解

            2.取bean
                    a.xml配置文件形式:
                        //获取IOC容器配置文件
                             ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
                        //拿bean对象
                             Speccontext.getBean("bean对象id值");

                    b.配置类的形式:
                        //获取IOC容器配置类
                             ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
                        //从容器中获取bean对象
                             Student stu = (Student)context.getBean("myStudent");


配置类的形式存bean:

                1.必须有@Configuration注解(配置类)

                2.形式:
                        三层组件:
                                a.给三层组件分别加注解(@Controller、@Service、@Repository  或可以使用@Component一个注解)
                                b.将注解所在包 纳入IOC扫描器(ComponentScan)
                                     ①使用配置文件applicatonContext.xml添加扫描器:
                                            如:
                                                <context:component-scan base-package="org.neowang.*">
                                                </context:component-scan>
                                     ②使用配置类添加扫描器:
                                            在配置类上加注解@ComponentScan(value="要扫描的包名")

                        非三层组件
                                a.方法前使用@Bean注解,该bean的id值默认就是方法名(但,可以通过@Bean("id值")来修改)
                                b. import \ FactoryBean等方式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值