Spring 配置Bean
来源:互联网 发布:淘宝客开发平台 编辑:程序博客网 时间:2024/05/22 13:54
**
Spring 配置Bean
**
1.配置形式 :基于XML文件的方式;基于注解的方式
2.Bean的配置方式 :通过全类名(反射),通过工厂方法,FactoryBean。
3.依赖注入的方式:属性注入,构造器注入
例:
3.1属性注入
applicationContext.xml
<!--配置bean--> <bean id="helloWorld" class ="全类名"> <!--通过setter方法注入--> <property name="name2" value="spring"></property> </bean>
3.2 构造器注入
<!--通过构造方法来配置bean的属性--> <!--可以指定参数的位置和参数的类型,以区分重载的构造器--> <bean id="car" class="全类名"> <constructor-arg value="Audi" index="0"></constructor-arg> <constructor-arg value="ShangHai" index="1"></constructor-arg> <constructor-arg value="30000" index="2"></constructor-arg> <constructor-arg value="240" type="int"></constructor-arg> </bean>
public class Main{ public static void main(String args[]) { //创建spring的IOC容器对象 ApplicationContext ctx = new ClassPathXmlApplcationContext("applicationContext.xml"); //从IOC容器中获取Bean实例 HelloWorld helloWorld=(HelloWorld) ctx.getBean("helloWorld"); HelloWorld helloWorld= ctx.getBean(HelloWorld.class);//不能保证唯一 System.out.println(helloWorld); // Car car = (Car) ctx.getBean("car"); } }
//Bean对象public class Car{ private String Brand; private String corp; private double price; private int maxSpeed; public Car(String brand,String corp,int pprice){ super(); this.brand = brand; this.corp = corp; this.price = price; } public String toString(){ return "Car[brand="+brand+",corp="+corp+",price="+price+",maxSpeed="+maxSpeed+"]"; }}
注意: id: 标识容器中bean,id唯一
class: bean的全类名,通过反射的方式在 IOC容器中创建Bean,要求Bean中必须有无参的构造器
4.IOC容器
ApplicationContext 代表IOC容器,实际上是一个接口
BeanFactory:IOC容器的基本实现,面向spring本身的
ApplicationCOntext:提供了更多的高级特性(直接使用这个)
配置Bean之前,必须先实例化IOC容器,只有实例化后,才可以从IOC里获取Bean实例使用
ApplicationContext的主要实现类:
ClassPathXmlApplicationContext:从类路径下加载配置文件
FileSystemXmlApplicationContext:从文件系统中加载配置文件
ApplicationContext 在初始化上下文时就实例化所有单例的Bean
阅读全文
1 0
- spring bean的配置
- Spring Bean 配置说明
- Spring 中的 Bean 配置
- Spring Bean 配置说明
- Spring配置bean属性
- Spring Bean配置示例
- Spring Bean配置继承
- spring 配置bean
- spring FactoryBean配置Bean
- Spring之Bean配置
- Spring 配置Bean
- 10003---Spring--配置Bean
- Spring -- 注解配置Bean
- spring 注解配置bean
- 配置Spring bean
- Spring-bean基础配置
- Spring-Bean配置-SpEL
- Spring bean的配置
- windows搭建redis java简易访问客户端
- 过程管理
- Vijos 1304 回文数 题解
- 弱者都自大暴躁,强者都低调温柔
- 谢天谢地我们还焦虑
- Spring 配置Bean
- 我们人人都有精神病,努力要做的是…
- 忽略没来由的中伤,藏好对远方的幻…
- 把天聊死是一种怎样的感觉
- 肢体勤奋,才是你失败的真正原因
- 蓝桥杯—字符逆序
- 这种鸡汤,胜过万两砒霜
- 这样做,才能留住员工的心
- 你听过的最无奈的一句话是什么?