spring5.0 java_spring5.0源码笔记

spring底层主要IOC容器和AOP,IOC底层存储对象的容器是一个线程安全的ConcurrentHashMap容器,即下面这段。

private final Map singletonObjects = new ConcurrentHashMap(256);

Configuration注解:

首先来说下xml形式的IOC注入。注意容器的id是不允许重复的,重复启动会报错。用@AllArgsConstructor注解的构造函数在xml模式无效,会报错,需要手写一个有参构造函数才行。

注解方式注入,可以采用下面方式来注入,默认以方法的名称为容器id(userEntity)。

//这里添加的Configuration注解,等同于spring xml文件配置的IOC

@Configuration

public class MySpringConfig {

@Bean

public UserEntity userEntity() {

return new UserEntity("哈哈", 20);

}

}

xml和注解方式的注入启动方式。AnnotationConfigApplicationContext划重点,面试要问。。。

//定义成全局的xml文件方式注入

private static ClassPathXmlApplicationContext applicationContext;

//定义成全局的注解方式的注入

private static AnnotationConfigApplicationContext annotationConfigApplicationContext;

public static void main(String[] args) {

//xml文件方式注入

applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

UserEntity userEntity = applicationContext.getBean("userEntity", UserEntity.class);

System.out.println(userEntity);

//注解方式注入

annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MySpringConfig.class);

UserEntity userEntity1 = annotationConfigApplicationContext.getBean("userEntity", UserEntity.class);

System.out.println(userEntity1);

}

延申至springboot中的一个注解:@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类。因此可以直接在@SpringBootApplication注解的类下直接写@Bean注解即可注入。

ComponentScan注解:

我们在写三层的时候,比如控制器层的类都添加一个@Controller注解,Service层的类都添加一个@Service注解,数据访问层都添加一个@Repository注解,那么这些类怎么交给spring管理呢,就用到了@ComponentScan注解,定义只要在指定包下面的都会注入到spring容器中去。然后就可以用getBean方法来获取注入对象的信息了。

//获取到所有注入的对象

String[] definitionNames=annotationConfigApplicationContext.getBeanDefinitionNames();

spring中ioc对象默认是单例的,@Scop注解可以指定对象生命周期。

@Scope("singleton")

singleton:全局有且仅有一个实例,默认的方式。

prototype:每次获取Bean的时候都会有一个新的实例。

request:表示针对每次请求都会产生一个新的Bean对象,并且该Bean对象仅在当前Http请求内有效。

session:作用域表示每次请求都会产生一个新的Bean对象,并且该Bean仅在当前Http session内有效。

未完待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值