下面 我们介绍 bean中的部分属性:
1.
lazy-init(默认为“default”):用来定义这个Bean是否实现懒初始化。
也就是说lazy-init=”true”的bean,IoC容器启动时不会实例化该bean,只有当容器需要用到时才实例化它。lazy-init有利于容器效率,对于不需要的bean可以先不管。
2.autowire(自动装配,默认为“default”):它定义了Bean的自动装载方式。
1、“no”:不使用自动装配功能。
2、“byName”:通过Bean的属性名实现自动装配。
3、“byType”:通过Bean的类型实现自动装配。
4、“constructor”:类似于byType,但它是用于构造函数的参数的自动组装。
5、“autodetect”:通过Bean类的反省机制(introspection)决定是使用“constructor”还是使用“byType”。
3.scope 就是用来配置 spring bean 的作用域,它标识 bean 的作用域。
(1).当一个bean的 作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。
(2).prototype作用域部署的bean,每一次请求(将其注入到另一个bean中,或者以程序的方式调用容器的 getBean()方法)都会产生一个新的bean实例,相当与一个new的操作。
将这几个属性用到代码中:
package test_spring2;
public class User {
private int age;
private String name;
private Dog dog1;
public User() {
}
public User(int age,String name){
this.age = age;
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", dog=" + dog1 + "]";
}
public void setDog1(Dog dog) {
this.dog1 = dog;
}
}
package test_spring2;
public class Dog {
public Dog() {
System.out.println("dog。。。。。。。");
}
}
进行如下 配置
<bean id="dog" class="test_spring2.Dog" lazy-init="true"
scope="prototype"/>
<!--byName byType -->
<bean id="user" class="test_spring2.User" autowire="byType">
</bean>
在Test中进行如下测试 :
测试 scope
当 配置bean 时 没有 配置scope 默认是单例模式,即scope=”singleton”
我们进行如下测试:
结果显示为:
当添加这个属性
结果为: