1、创建一个xml格式的配置文件
2、在xml文件中定义一个bean,给每个bean设定一个id
3、通过ApplicationContext获取Spring上下文ApplicationContext context = new ClassPathXmlApplicatioinContext("文件名.xml");
4、获取beanBean bean = context.getBeal("第一步中给bean的id",Bean.class);

spring ioc
创建一个xml配置文件
获取spring上下文
获取bean
1-4 Spring IoC入门





xml配置spring

将bean交给spring管理

如何实例化一个bean?

通过配置xml文件获取bean

把一个Java bean交由spring来管理,分三个步骤:
创建一个xml配置文件。
将一个Bean交由Spring创建并管理。
获取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"> <bean class="com.imooc.spring.ioc.class.Bean1" id="bean1"/> </beans>
需要依赖的jar包:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> </dependencies>
把一个Java bean交由spring来管理,分三个步骤:
创建一个xml配置文件。
将一个Bean交由Spring创建并管理。
获取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"> <bean class="com.imooc.spring.ioc.class.Bean1" id="bean1"/> </beans>
如何使用在spring.xml文件中创建的bean:
//获取spring.xml的上下文
ApplicationContext context=new ClassPathXmlApplicationContext("spring.cml");
//从中获取bean
context.getBean("bean",Bean.class);
System.out.println("bean = " + bean);
创建bean,需要在resources中创建spring.xml
该文件头,如图。
如果我们想将一个java bean交由spring来管理的话,需要在文件中定义一个节点
<bean id="bean" class="com.imooc.spring.ioc.class004.Bean"></bean>
通过springIoc管理bean的方法:
创建一个spring xml文件
通过spring xml文件来管理Bean
使用ClassPathXmlApplicationContext来读取xml文件,获取Spring的上下文
获取Bean的相关内容
Spring的xml方式获取bean
1、创建一个xml配置文件
2、创建一个bean,并交由Spring管理
3、获取Spring上下文
4、获取bean
使用spring管理Bean的步骤
Spring IoC 入门
使用Spring IoC
spring基本使用
然后通过applicationcontext读取xml配置文件,
然后获取spring的上下文
最后通过context.getBean方法获取bean就可以
第二步在xml文件里定义bean
要把javabean交由spring来管理,需要几个步骤
1.需要创建一个xml格式的配置文件
有正确的结果输出
输出bean
指定beanid返回哪一个类的类型
通过spring上下文获取一个bean
ggdgggd
接下来如何使用?
如果我们要将javabean交给spring来管理,要在xml文件里建立一个节点,指定要管理的bean