(一)spring的bean简单的配置
2017-10-18 20:32
239 查看
第一步:建立一个类
第二部配置资源文件
第三步:main方法中获取bean
第四步:运行main方法,得到打印结果
package com.atguigu.spring.beans; public class HelloWorld { private String name; public void setName(String name){ this.name=name; } public void hello(){ System.out.println("hello:"+name); } }
第二部配置资源文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!--配置bean class:bean的全类名通过反射的方式在IOC容器中创建Bean所以要求Bean中必须有无参的构造器 --> <bean id="h" class="com.atguigu.spring.beans.HelloWorld"> <property name="name" value="Spring----》fangxinde,you are successful"></property> </bean> </beans>
第三步:main方法中获取bean
package com.atguigu.spring.beans; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //ClassPathXmlApplicationContext接口的实现类,该实现类从类路径下来加载配置文件 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); //利用类型返回IOC容器中的Bean,但要求IOC容器中必须智能一个该类型的Bean HelloWorld helloworld=ctx.getBean(HelloWorld.class); //HelloWorld helloworld=(HelloWorld) ctx.getBean("helloworld1"); helloworld.hello(); } }
第四步:运行main方法,得到打印结果
hello:Spring----》fangxinde,you are successful
相关文章推荐
- [Spring]配置简单Bean详解
- Spring简单配置-基于工厂模式装载bean
- Spring-简单bean的配置(使用bean.xml手动完成)
- Spring简单实用bean配置
- servlet调用spring容器中的bean,的两种方式一种注解一种xml配置
- Spring开发--Bean配置实例讲解
- Spring配置--Bean之间的关系(继承和依赖)
- 简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例
- 搭建简单web项目: spring3.0基础配置(1)
- 基于java的Spring容器配置(二)(@Configuration,@Bean,@Import,@ImportSource)
- spring 简单实现BeanFactory(转)
- Spring源码阅读——简单模拟Spring的控制反转IOC和依赖注入(Bean的加载和获取)
- spring管理属性配置文件properties——使用PropertiesFactoryBean
- spring配置工厂bean
- Atitit ioc 之道 attilax著 第2章 装配Bean 33 2.1 Spring配置的可选方案 34 2.2 自动化装配bean 35 2.2.1 创建可被发现的bean 35 2.
- Spring学习笔记 使用XML配置实现Bean的auto-wiring (自动绑定)
- spring中bean配置和bean注入
- spring 配置bean-自动装配
- Spring配置使用注解注入bean
- Spring配置bean的方法(工厂方法和Factorybean)