spring中bean的配置

来源:互联网 发布:淘宝商品级和sku级 编辑:程序博客网 时间:2024/05/18 03:22

IOC:反转控制

DI:组件以一些预定的方式(setter)接收来自容器的资源注入,依赖容器把资源给我注入。

bean配置的形式:xml配置和注解配置

bean的配置方式:全类名(java反射的机制),工厂方法,factoryBean

IOC容器:applicationCOntext, beanFactory

依赖注入的方式:属性注入,构造注入,接口注入(了解)

<bean id="hello" class="com.my.beans.HelloWord">
<property name="name1" value="zhangsan"></property>
</bean>

applicationContext中的bean节点。id,class通过class标识的全类名用java反射的机制创建bean的对象,并将对象标识符为id的值,供在java代码中通过容器对象的getBean("id")引用。

property是给该bean的属性初始化值name对应于javabean的属性名字;所以要求javabean中必须有一个无惨构造方法。

applicationContext是一个接口。有两个主要的实现类:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC中获取bean实例
HelloWord hello = (HelloWord) context.getBean("hello");

ClassPathXmlApplicationContext是在类路径下的xml格式找到applicationContext(类路径是在src下),还有文件系统中加载文件

sping中的属性注入:就是通过bean的setter方法为bean设置属性值或依赖的对象(引用,在A中有B类型的属性)。

属性注入使用property标签,name指定bean的名字,value指定赋予的值。

value还可以作为子节点。

<constructor type="java.lang.string">

<value>444</value>

</constructor>

当value中有特殊的字符的时候可以使用:要显示<beijing> 可以通过:<value><![CDATA[<beijing>]]></value>

当bean之间存在引用的时候:people 和car之间:

<bean id="car" class="com.my.beans.Car">
<property name="brand" value="baoma"></property>
<property name="maxSpeed" value="250.0"></property>
<property name="price">
<value>300000</value>
</property>
</bean>

<bean id="people" class="com.my.beans.People">
<property name="age" value="55"></property>
<property name="name" value="zhangsan"></property>
<property name="car" ref="car"></property>
</bean>

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
People car=(People) context.getBean("people");
System.out.println(car.toString());
}

People [age=55, name=zhangsan, car=Car [Brand=baoma, price=300000.0, maxSpeed=250.0]]


内部bean:

在property之间没有引用外部的而是直接在里面写一个bean,内部bean不可被外部引用

<bean id="people" class="com.people">

<property  name="name" value="lisi"></property>

<property name=car>

<!--不要ref引用了,直接在里面写一个bean-->

<bean class="com.car">

<property name="brand" value="aodo"></property>

<property name="price" value="200000"></property>

</bean>

等价于<property name="car" ref="car"></property>

</property>

<.bean>

当附一个null值的时候构造器传入值为<null/>特殊的专有

为级联属性赋值:proplebean中的<property name="car.maxspeed" value="120"/>











0 0
原创粉丝点击