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内有效。
未完待续。。。