一、Spring容器继承图
二、往IoC容器添加bean方式
2.1 基于xml定义Bean
2.1.1 在工程的resources目录下新建文件beans.xml,配置如下代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.mxf.ioc.base.service.People"></bean>
</beans>
2.1.2 创建main方法执行如下代码:
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
System.out.println(applicationContext.getBean("person"));
}
2.1.3 执行结果如下:
2.2 基于配置类定义Bean
2.2.1 在工程下新建MainConfig类,代码如下:
@Configuration
public class MainConfig {
@Bean
public People people(){
return new People();
}
}
bean的默认名称是方法名,也可以通过@Bean(value="bean name")指定。
2.2.2 创建Main方法执行如下代码:
public class MainApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println(applicationContext.getBean("people"));
}
2.2.3 执行结果如下:
2.3 通过@ComponentScan注解来进行包扫描
需要和@Controller @Service @Component @Respository注解组合
@ComponentScan(basePackages = {"com.mxf.ioc"},
excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class}),
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Service.class}),
@ComponentScan.Filter(type = FilterType.CUSTOM, value = {CustomFilterType.class})},
useDefaultFilters = false)
excludeFilters排除Controller注解,includeFilters包含注解,若使用includeFilters或者FilterType.CUSTOM时,需设置useDefaultFilters = false。
2.3.1 自定义FilterFilter
public class CustomFilterType implements TypeFilter {
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
AnnotatedTypeMetadata annotatedTypeMetadata = metadataReader.getAnnotationMetadata();
Resource resource = metadataReader.getResource();
ClassMetadata classMetadata = metadataReader.getClassMetadata();
if(classMetadata.getClassName().contains("Controller")){
return true;
}
return false;
}
}
2.4 通过@Import来导入bean
@Import(value = {StudentImportSelector.class, com.mxf.ioc.base.Person.class, StudentBeanDefinitionRegister.class})
@Configuration
public class MainConfig {
}
2.5 通过ImportSelector
public class StudentImportSelector implements ImportSelector {
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"com.mxf.ioc.base.service.TestService"};
}
}
2.6 通过ImportBeanDefinitionRegistrar
public class StudentBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
// 创建一个bean对象
RootBeanDefinition beanDefinition = new RootBeanDefinition(TestController.class);
// 把bean对象注册到容器中
beanDefinitionRegistry.registerBeanDefinition("testController", beanDefinition);
}
}
2.7 通过FacotryBean
public class StudentFactoryBean implements FactoryBean<Student> {
public Student getObject() throws Exception {
return new Student();
}
public Class<?> getObjectType() {
return Student.class;
}
public boolean isSingleton() {
return true;
}
}
三、 Spring的生命周期
bean的实例化、初始化、销毁等完整流程。
2.1 init和destroy方法
@Configuration
public class MainConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public People people(){
return new People();
}
}
2.2 实现InitializingBean和DisposableBean
public class People implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
}
@Override
public void destroy() throws Exception {
}
}
2.3 实现@PostConstruct 和@PreDestory
public class People{
@PostConstruct
public void init(){
}
@PreDestroy
public void destroy(){
}
}
2.4 通过BeanPostProcessor
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
2.5 通过@Value +@PropertySource来给组件赋值
2.5.1 在resources目录下新建person.properties文件
person.lastName=jerry
2.5.2 指定外部文件位置
@PropertySource(value = {"classpath:person.properties"})
@Configuration
public class MainConfig {
@Bean
public Person1 person1(){
return new Person1();
}
}
```
@Data
public class Person1 {
@Value("tom")
private String firstName;
@Value("#{28-8}")
private Integer age;
@Value("${person.lastName}")
private String lastName;
}
```