spring学习笔记(一)

本文介绍了Spring框架中的IOC(控制反转)概念,演示了如何使用Spring容器实例化对象,并提供了具体的代码示例。同时,文章详细展示了配置文件的定义方式,帮助读者理解如何通过XML配置文件指定由Spring容器管理的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOC: 控制反转:

          将对象的实例化交给spring 容器来完成。


1.启动框架

     

//BeanFactory: spring 容器,XmlBeanFactory:通过xml配置的spring工厂
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);


2. 从容器中拿bean

  a. 按照类型拿bean

factory.getBean(HelloWorld.class);


  b. 按照名字拿bean

hello=(HelloWorld)factory.getBean("hello");


  c. 按照名字和类型拿bean

hello=factory.getBean("hello", HelloWorld.class);


spring容器要实例化哪些bean,需要在配置文件中进行声明。


          

<?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 实力化(管理)的对象 
   id: 给bean 起一个唯一的名字,为了从spring 容器中拿对象
   

-->
<bean id="hello" class="com.zhq.controller.HelloWorld">

</bean>
    
</beans>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值