规则1:Spring默认管理对象都是单例的
规则2:通过@Scope注解,控制对象单例/多例
1.2懒加载机制 1.2.1懒加载说明说明:如果Spring容器创建对象立即创建,则该加载方式为,立即加载 容器启动时创建
如果Spring容器创建,对象在被使用的时候才加载 则称之为懒加载 用时才加载
注释:@Lazy 添加表示改为懒加载
测试说明: 主要测试对象中的无参构造什么时候执行
1.2.3多例与懒加载的关系
说明:只要对象是多例模式都是懒加载!!!! ,在单例模式中控制懒汉式加载才"有效"
规则说明:
lazy true lazy false
单例模式: 有效 有效 立即加载
多例模式: 无效 懒加载 无效 懒加载
1.2.4关于lazy使用场景的说明场景1: 服务器启动时,如果加载太多的资源,则必然导致服务器启动慢,适当的将不重要的资源设置为懒加载
场景2: 有时用户需要一些特殊的链接,而这些链接的创建需要很长的时间,可以使用懒加载.
1.3Spring生命周期的管理1.3.1关于生命周期的说明
说明:一个对象从创建到消亡,可以划分为四个阶段,如果需要对程序进行干预,则可以通过周期方法进行干预(回调函数/钩子函数/接口回调)
四大阶段图解说明生命周期
1.3.2生命周期函数方法的使用@PostConstruct: 在对象创建之后立即调用
@PerDestroy: 对象消亡时 进行调用
编辑配置类package com.jt.config;
import com.jt.demo.User;
import org.springframework.context.annotation.*;
@Configuration//这是一个配置类标识
@ComponentScan("com.jt")
public class SpringConfig {
@Bean
// @Scope("singleton")//默认值,单例模式
@Scope("prototype")//多例模式
//@Lazy//懒加载
public User user(){
return new User();
}
}
编辑生命周期类
package com.jt.demo;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class Person {
public Person(){
System.out.println("SR出生了 智商拉曼");
}
@PostConstruct
public void init(){
System.out.println("SR长大了 骨骼精奇");
}
public void dowork(){
System.out.println("SR迎娶WR");
}
@PreDestroy
public void destory(){
System.out.println("找一块风水宝地一起埋葬");
}
}
编辑测试类
@Test
public void testdemo2(){
//容器启动对象创建
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfig.class);
//从容器中获取对象(要用)
Person person = context.getBean(Person.class);
person.dowork();
context.close();
1.4 依赖注入(Dependency Injection,简称DI)
1.4.1创建结构
1.准备User类
2.准备Dog类
3.Cat类
说明:Dog和Cat向User类注入功能
1.4.2: 2@Autowired注解说明:在对象中如果需要使用属性注入,一般使用@Autowired注解
功能: 可以将Spring容器中的对象,自动注入到属性中.
注入方式:
1.默认按照类型注入, 如果注入的属性是接口,则自动注入实现类
2.按照类型注入
重要的前提:如果需要依赖注入,则对象必须交给容器管理
编辑配置类package com.jt.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //标识我是配置类
@ComponentScan("com.jt")//必须添加包路径
public class SpringConFig {
}
编辑接口pet类
package com.jt.demo;
public interface pet {
public void hello();
编辑User类并加依赖注入@Auto
package com.jt.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component//将User交给容器管理
public class User {
@Autowired
private pet pet;
public void say(){
//调用宠物的方法
pet.hello();
}
}
编辑Cat类并实现pet接口
package com.jt.demo;
import org.springframework.stereotype.Component;
@Component
public class Cat implements pet{
@Override
public void hello() {
System.out.println("小猫喵喵咪");
}
}
1.5接口多实现的情况说明
1.5.1代码说明
说明:
1.5.2报错说明
说明:一个接口只有一个实现类,否则Spring程序无法选择
@Autowired
@Qualifier("cat")//该注解不能单独使用 如果要用必修须配合@Autowired一起使用,
// 根据key进行注入
1.6@Resource注解说明
一般不用 因为他是javax下的 我们只用Spring的



