注解
1、起一个标志的作用
2、注解不能单独存在
3、注解使用的位置
1 | public enum ElementType { |
听海观潮
Student类和Person类:
1 | public class Student{ |
装载属性配置如下:
1 | <bean id="student" class="..." scope="prototype"></bean> |
注意:
如果在student对象scope对象配置为prototype,在student类的构造方法中写入输出student语句,将会打印出4个student。
第一个因为有ref引用,spring将对象创建提前了,创建了一个student对象;
后面三个是一个ref创建一个student对象;
DI:依赖注入
概念:给属性赋值
public class Student{
}
public class Person{
private Long pid;
private String name;
private Student student;
private List list;
private Set set;
private Map map;
private Properties properties;
}
步骤:
执行流程:
4、给person对象中的属性进行装配的操作
注意:
如果把Student的配置方式改成scope=”prototype”,
因为其他的类的创建和属性的装配的过程全部发生在spring容器启动的时候,所以Student对象的创建被提前了
,但是还是用一次即创建一次对象
public class HelloWorld {
public HelloWorld(){
System.out.println("hello world");
}
public void init(){
System.out.println("init");
}
public void destroy(){
System.out.println("destroy");
}
public void hello(){
System.out.println("hello");
}
}
<bean id="helloWorld"
class="com.ithiema07.spring.ioc.initdestroy.HelloWorld"
init-method="init"
destroy-method="destroy"></bean>
4、执行destroy方法
该方法是由spring容器内部调用的
前提:在spring容器关闭的时候执行,仅单例
注意点:如果一个bean是多例,则spring容器不负责销毁
1、启动spring容器
1、配置文件如下:1
2<bean id="helloWorld" class="..." ></bean>
<bean id="helloWorld2" class="..." ></bean>
说明:
1、只要声明一个bean,spring容器就会为之创建对象,不管class是否相同
2、在默认情况下,在启动spring容器的时候创建对象
3、把service层和dao层所有的类放入spring容器中,在启动spring容器的时候创建对象
4、可以过早的检查发现错误
5、缺点:如果该类中有属性,并且属性为一个集合,那么在创建对象的时候,集合中如果有数据了,那么该数据会过早的加入到内存中
为了避免上述情况的发生,尽量把数据放在局部变量中
(通过代理来做,需要的时候再加载)1
2
3
4
5
6
7
8
9
10@Component
public class SystemProperties{
private Properties properties;
@PostConstruct
public void initProperties(){
properties = ...;
}
}
系统初始化的时候,加载数据库系统配置文件到Properties类中
2、配置延迟加载:1
<bean id="helloWorld" class="..." lazy-init="true"></bean>
default:默认=否
false:否,spring启动时创建对象
ture:是,调用时才创建对象
在多例的情况下,不论是否设置lazy-init,都是在调用的时候才创建对象1
<bean id="helloWorld" class="..." scope="prototype" lazy-init="ture"></bean>