IOC
Inverse of COntrol,反转控制
相关依赖:spring-context
AOP
Aspect Oriented Programming,面向切面编程
@Configuration与@Bean的用法
告诉spring这是一个配置类,并将bean依赖注入
@ComponentScan: 告诉spring需要扫描的包
@Configuration // 告诉spring这是一个配置类
@ComponentScan(value = "com.atguigu",
/* excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})
},*/
includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
},
useDefaultFilters = false
)
public class MainConfig {
/*
* <bean id="person" class="com.atguigu.bean.Person">
<property name="age" value="18"></property>
<property name="name" value="zhangsan"></property>
</bean>
*
* */
@Bean(value = "person02")
public Person person() { // spring 默认会把方法名作为bean id,如果想改bean名称,可以Bean中加
return new Person("lisi", 20);
}
}
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanNames = applicationContext.getBeanDefinitionNames(); # 获取所有的注解
String[] namesForType = applicationContext.getBeanNamesForType(Person.class); # 获取Person类型的注解的名称
@ComponentScan注解中过滤规则
001. 表示包扫描的时候需要过滤掉的
type = FilterType.ANNOTATION表示根据注解类型过滤
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})
}
002. 表示扫描时需要留下来的,
type = FilterType.ASSIGNABLE_TYPE表示根据类名过滤
type = FilterType.CUSTOM表示根据自定义类型过滤
includeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {BookService.class}),
@Filter(type = FilterType.CUSTOM, classes = {MyTypeFilter.class})
},
useDefaultFilters = false, 表示不使用默认的过来规则,否则定义的Filter将不会起作用
)
@Scope调整作用域
spring中默认注入的依赖是单例模式
@Bean
public Person person() {
System.out.println("给容器中添加Person......");
return new Person("zhangsan", 25);
}
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
Person person01 = applicationContext.getBean("person", Person.class);
Person person02 = applicationContext.getBean("person", Person.class);
System.out.println(person01 == person02);//true spring中注入的依赖,默认都是单例的
懒加载:
由于单实例bean:默认再容器使用的时候创建对象;
懒加载:容器启动时不创建对象,第一次使用时才创建;
@Lazy
给容器中注册组件:
1. 包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)
2. @Bean导入的第三方包里面的组件
3. @Import[快速给容器中导入一个组件]
3.1 @Import(要导入到容器中的组件),容器中就会自动注册这个组件,id默认是全类名
3.2 ImportSelector:返回需要导入的组件的全类名数组;
4. 使用Spring提供的FactoryBean