Spring底层核心架构

Spring底层核心架构

相关的配置类
1. user类

package com.zhouyu.service;import org.springframework.stereotype.Component;public class User {
}

2. AppConfig类

package com.zhouyu;import org.springframework.context.annotation.*;
import org.springframework.scheduling.annotation.EnableScheduling;import javax.sql.DataSource;@ComponentScan("com.zhouyu")
@EnableScheduling
@PropertySource("classpath:spring.properties")
public class AppConfig {}

3.spring.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"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"><context:component-scan base-package="com.zhouyu"/><bean id="user1" class="com.zhouyu.service.User" scope="prototype"/>
</beans>

在这里插入图片描述

1.BeanDefinition

  • class,表示Bean类型
  • scope,表示Bean作用域,单例或原型等
  • lazyInit:表示Bean是否是懒加载
  • initMethodName:表示Bean初始化时要执行的方法
  • destroyMethodName:表示Bean销毁时要执行的方法
  • 还有很多…

(1)BeanDefinition简单使用

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();beanDefinition.setBeanClass(User.class);context.registerBeanDefinition("user", beanDefinition);System.out.println(context.getBean("user"));}
}

在这里插入图片描述
在这里插入图片描述
说明:AbstractBeanDefinition可以把对象注册到spring容器中。

2.BeanDefinition设置相关的属性

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();beanDefinition.setBeanClass(User.class);beanDefinition.setScope("prototype"); // 设置作用域//beanDefinition.setInitMethodName("init"); // 设置初始化方法beanDefinition.setLazyInit(true); // 设置懒加载context.registerBeanDefinition("user", beanDefinition);System.out.println(context.getBean("user"));System.out.println(context.getBean("user"));}
}

在这里插入图片描述
在这里插入图片描述

2.BeanDefinitionReader

1.BeanDefinitionReader简单使用

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);AnnotatedBeanDefinitionReader annotatedBeanDefinitionReader = new AnnotatedBeanDefinitionReader(context);annotatedBeanDefinitionReader.register(User.class);System.out.println(context.getBean("user"));}
}

在这里插入图片描述

3.XmlBeanDefinitionReader

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(context);int i = xmlBeanDefinitionReader.loadBeanDefinitions("spring.xml");System.out.println(context.getBean("user"));}
}

在这里插入图片描述

4.ClassPathBeanDefinitionScanner

package com.zhouyu;import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();context.refresh();ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);scanner.scan("com.zhouyu");System.out.println(context.getBean("userService"));}
}

在这里插入图片描述

5.BeanFactory

1.DefaultListableBeanFactory的使用

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;public class Test {public static void main(String[] args) {DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();beanDefinition.setBeanClass(User.class);beanFactory.registerBeanDefinition("user", beanDefinition);System.out.println(beanFactory.getBean("user"));}
}

在这里插入图片描述
在这里插入图片描述
它实现了很多接口,表示,它拥有很多功能:

  1. AliasRegistry:支持别名功能,一个名字可以对应多个别名
  2. BeanDefinitionRegistry:可以注册、保存、移除、获取某个BeanDefinition
  3. BeanFactory:Bean工厂,可以根据某个bean的名字、或类型、或别名获取某个Bean对象
  4. SingletonBeanRegistry:可以直接注册、获取某个单例Bean
  5. SimpleAliasRegistry:它是一个类,实现了AliasRegistry接口中所定义的功能,支持别名功能
  6. ListableBeanFactory:在BeanFactory的基础上,增加了其他功能,可以获取所有BeanDefinition的beanNames,可以根据某个类型获取对应的beanNames,可以根据某个类型获取{类型:对应的Bean}的映射关系
  7. HierarchicalBeanFactory:在BeanFactory的基础上,添加了获取父BeanFactory的功能
  8. DefaultSingletonBeanRegistry:它是一个类,实现了SingletonBeanRegistry接口,拥有了直接注册、获取某个单例Bean的功能
  9. ConfigurableBeanFactory:在HierarchicalBeanFactory和SingletonBeanRegistry的基础上,添加了设置父BeanFactory、类加载器(表示可以指定某个类加载器进行类的加载)、设置Spring EL表达式解析器(表示该BeanFactory可以解析EL表达式)、设置类型转化服务(表示该BeanFactory可以进行类型转化)、可以添加BeanPostProcessor(表示该BeanFactory支持Bean的后置处理器),可以合并BeanDefinition,可以销毁某个Bean等等功能
  10. FactoryBeanRegistrySupport:支持了FactoryBean的功能
  11. AutowireCapableBeanFactory:是直接继承了BeanFactory,在BeanFactory的基础上,支持在创建Bean的过程中能对Bean进行自动装配
  12. AbstractBeanFactory:实现了ConfigurableBeanFactory接口,继承了FactoryBeanRegistrySupport,这个BeanFactory的功能已经很全面了,但是不能自动装配和获取beanNames
  13. ConfigurableListableBeanFactory:继承了ListableBeanFactory、AutowireCapableBeanFactory、ConfigurableBeanFactory
  14. AbstractAutowireCapableBeanFactory:继承了AbstractBeanFactory,实现了AutowireCapableBeanFactory,拥有了自动装配的功能
  15. DefaultListableBeanFactory:继承了AbstractAutowireCapableBeanFactory,实现了ConfigurableListableBeanFactory接口和BeanDefinitionRegistry接口,所以DefaultListableBeanFactory的功能很强大

6.ApplicationContext

1.AnnotationConfigApplicationContext

package com.zhouyu;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(AppConfig.class);//是否包含beanSystem.out.println(applicationContext.containsBean("user"));System.out.println(applicationContext.containsBean("userService"));//获取所有名字for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}

在这里插入图片描述

2.AnnotationConfigApplicationContext

package com.zhouyu;import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");//是否包含beanSystem.out.println(applicationContext.containsBean("user"));System.out.println(applicationContext.containsBean("userService"));//获取所有名字for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {System.out.println(beanDefinitionName);}}
}

在这里插入图片描述
在这里插入图片描述

3.国际化

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
AppConfig

package com.zhouyu;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.scheduling.annotation.EnableScheduling;@ComponentScan("com.zhouyu")
@EnableScheduling
@PropertySource("classpath:spring.properties")
public class AppConfig {@Beanpublic MessageSource messageSource() {ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.setBasename("message");return messageSource;}
}

UserService

package com.zhouyu.service;import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Locale;@Component
public class UserService implements ApplicationContextAware {@Autowiredprivate OrderService orderService;private ApplicationContext applicationContext;public void test(){System.out.println(applicationContext.getMessage("test", null, new Locale("de")));}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}
}

Test

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.Locale;public class Test {public static void main(String[] args) {ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);UserService userService =(UserService) context.getBean("userService");userService.test();}
}

在这里插入图片描述

4.资源加载

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;import java.io.IOException;
import java.util.Locale;public class Test {public static void main(String[] args) throws IOException {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Resource resource = context.getResource("file://E:\\Study\\spring-framework-5.3.10\\tuling\\src\\main\\resources");try {System.out.println(resource.contentLength());} catch (IOException e) {e.printStackTrace();}System.out.println("------------");Resource resource1 = context.getResource("https://www.baidu.com");System.out.println(resource1.contentLength());System.out.println(resource1.getURL());System.out.println("------------");Resource resource2 = context.getResource("classpath:spring.xml");System.out.println(resource2.contentLength());System.out.println(resource2.getURL());}
}

在这里插入图片描述

5.获取运行时环境

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.Resource;import java.io.IOException;
import java.util.Locale;
import java.util.Map;public class Test {public static void main(String[] args) throws IOException {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Map<String, Object> systemEnvironment = context.getEnvironment().getSystemEnvironment();System.out.println(systemEnvironment);System.out.println("=======");Map<String, Object> systemProperties = context.getEnvironment().getSystemProperties();System.out.println(systemProperties);System.out.println("=======");MutablePropertySources propertySources = context.getEnvironment().getPropertySources();System.out.println(propertySources);System.out.println("=======");System.out.println(context.getEnvironment().getProperty("NO_PROXY"));System.out.println(context.getEnvironment().getProperty("sun.jnu.encoding"));System.out.println(context.getEnvironment().getProperty("zhouyu"));}
}

在这里插入图片描述

6.事件发布

1.UserService

package com.zhouyu.service;import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Locale;@Component
public class UserService implements ApplicationContextAware {@Autowiredprivate OrderService orderService;private ApplicationContext applicationContext;public void test(){applicationContext.publishEvent("kkkk");}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}
}

2.AppConfig

package com.zhouyu;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.scheduling.annotation.EnableScheduling;@ComponentScan("com.zhouyu")
@EnableScheduling
@PropertySource("classpath:spring.properties")
public class AppConfig {@Beanpublic ApplicationListener applicationListener() {return new ApplicationListener() {@Overridepublic void onApplicationEvent(ApplicationEvent event) {System.out.println("接收到了一个事件:"+event.getSource());}};}
}

2.Test

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.Locale;public class Test {public static void main(String[] args) {ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);UserService userService =(UserService) context.getBean("userService");userService.test();}
}

在这里插入图片描述

7.类型转化

7.1在bean中使用

1.创建对象StringToUserPropertyEditor

package com.zhouyu;import com.zhouyu.service.User;import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:02*/
public class StringToUserPropertyEditor extends PropertyEditorSupport implements PropertyEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {User user = new User();user.setName(text);this.setValue(user);}
}

2.Test

package com.zhouyu;import com.zhouyu.service.User;
import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.Locale;public class Test {public static void main(String[] args) {StringToUserPropertyEditor propertyEditor = new StringToUserPropertyEditor();propertyEditor.setAsText("1");User value = (User) propertyEditor.getValue();System.out.println(value);}
}

在这里插入图片描述

7.2在Spring中使用

1.创建对象StringToUserPropertyEditor

package com.zhouyu;import com.zhouyu.service.User;import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:02*/
public class StringToUserPropertyEditor extends PropertyEditorSupport implements PropertyEditor {@Overridepublic void setAsText(String text) throws IllegalArgumentException {User user = new User();user.setName(text);this.setValue(user);}
}

**2.UserService **

package com.zhouyu.service;import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Locale;@Component
public class UserService implements ApplicationContextAware {@Autowiredprivate OrderService orderService;private ApplicationContext applicationContext;@Value("Nickel")private User user;public void test(){applicationContext.publishEvent("kkkk");System.out.println(user);}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}
}

3.Test

package com.zhouyu;import com.zhouyu.service.User;
import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import java.util.Locale;public class Test {public static void main(String[] args) {ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);UserService userService =(UserService) context.getBean("userService");userService.test();}
}

在这里插入图片描述

8.ConversionService

1.在bean中使用

1.创建对象

package com.zhouyu;import com.zhouyu.service.User;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;import java.util.Collections;
import java.util.Set;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:18*/
public class StringToUserConverter implements ConditionalGenericConverter {@Overridepublic boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {return sourceType.getType().equals(String.class) && targetType.getType().equals(User.class);}@Overridepublic Set<ConvertiblePair> getConvertibleTypes() {return Collections.singleton(new ConvertiblePair(String.class, User.class));}@Overridepublic Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {User user = new User();user.setName((String)source);return user;}
}

2.Test 使用

package com.zhouyu;import com.zhouyu.service.User;
import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.convert.support.DefaultConversionService;public class Test {public static void main(String[] args) {DefaultConversionService conversionService = new DefaultConversionService();conversionService.addConverter(new StringToUserConverter());User value = conversionService.convert("1", User.class);System.out.println(value);}
}

在这里插入图片描述

2.在spring中使用

**1.AppConfig配置 **

package com.zhouyu;
import com.zhouyu.service.User;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.scheduling.annotation.EnableScheduling;import java.beans.PropertyEditor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;@ComponentScan("com.zhouyu")
@EnableScheduling
@PropertySource("classpath:spring.properties")
public class AppConfig {@Beanpublic ConversionServiceFactoryBean conversionService() {ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();conversionServiceFactoryBean.setConverters(Collections.singleton(new StringToUserConverter()));return conversionServiceFactoryBean;}
}

**2.UserService 进行转化 **

package com.zhouyu.service;import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Locale;@Component
public class UserService implements ApplicationContextAware {@Autowiredprivate OrderService orderService;private ApplicationContext applicationContext;@Value("Nickel")private User user;public void test(){applicationContext.publishEvent("kkkk");System.out.println(user);}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}
}

**3.Test测试 **

package com.zhouyu;import com.zhouyu.service.User;
import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.convert.support.DefaultConversionService;public class Test {public static void main(String[] args) {ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);UserService userService =(UserService) context.getBean("userService");userService.test();}
}

在这里插入图片描述
说明:我们会看到很多地方都在使用,如‘com.zhouyu.service.User’的形式代表一个对象,这种场景就可以运用

8.TypeConverter

整合了PropertyEditor和ConversionService的功能,是Spring内部用的

SimpleTypeConverter typeConverter = new SimpleTypeConverter();typeConverter.registerCustomEditor(User.class, new StringToUserPropertyEditor());//typeConverter.setConversionService(conversionService);User value = typeConverter.convertIfNecessary("1", User.class);System.out.println(value);

9.OrderComparator

对象排序放到数组中
1.对象A

package com.zhouyu.service;import org.springframework.core.Ordered;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:33*/
public class A implements Ordered {@Overridepublic int getOrder() {return 3;}@Overridepublic String toString() {return this.getClass().getSimpleName();}
}

2.对象B

package com.zhouyu.service;import org.springframework.core.Ordered;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:33*/
public class B implements Ordered {@Overridepublic int getOrder() {return 2;}@Overridepublic String toString() {return this.getClass().getSimpleName();}
}

3.测试

package com.zhouyu;import com.zhouyu.service.A;
import com.zhouyu.service.B;
import org.springframework.core.OrderComparator;import java.util.ArrayList;
import java.util.List;public class Test {public static void main(String[] args) {
//		ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);
//		UserService userService =(UserService) context.getBean("userService");
//		userService.test();A a = new A(); // order=3B b = new B(); // order=2OrderComparator comparator = new OrderComparator();System.out.println(comparator.compare(a, b));  // 1List list = new ArrayList<>();list.add(a);list.add(b);// 按order值升序排序list.sort(comparator);System.out.println(list);  // B,A}
}

在这里插入图片描述
另外,Spring中还提供了一个OrderComparator的子类:AnnotationAwareOrderComparator,它支持用@Order来指定order值。比如:
1.A对象

package com.zhouyu.service;
import org.springframework.core.annotation.Order;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:33*/
@Order(3)
public class A {@Overridepublic String toString() {return this.getClass().getSimpleName();}
}

2.B对象

package com.zhouyu.service;import org.springframework.core.annotation.Order;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:33*/
@Order(2)
public class B{@Overridepublic String toString() {return this.getClass().getSimpleName();}
}

3测试方法

package com.zhouyu;import com.zhouyu.service.A;
import com.zhouyu.service.B;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;import java.util.ArrayList;
import java.util.List;public class Test {public static void main(String[] args) {A a = new A(); // order=3B b = new B(); // order=2AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator();System.out.println(comparator.compare(a, b)); // 1List list = new ArrayList<>();list.add(a);list.add(b);// 按order值升序排序list.sort(comparator);System.out.println(list); // B,A}
}

在这里插入图片描述

10.BeanPostProcessor

1.创建NickelBeanPostProcessor对象

package com.zhouyu;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:48*/
@Component
public class NickelBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {if ("userService".equals(beanName)) {System.out.println("初始化前");}return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {if ("userService".equals(beanName)) {System.out.println("初始化后");}return bean;}
}

2.Test

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {public static void main(String[] args) {ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);UserService userService =(UserService) context.getBean("userService");userService.test();}
}

在这里插入图片描述

11.BeanFactoryPostProcessor

BeanFactoryPostProcessor表示Bean工厂的后置处理器,其实和BeanPostProcessor类似,BeanPostProcessor是干涉Bean的创建过程,BeanFactoryPostProcessor是干涉BeanFactory的创建过程。比如,我们可以这样定义一个BeanFactoryPostProcessor:

package com.zhouyu;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:52*/
@Component
public class NickelBeanFactoryPostProcessor implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {System.out.println("加工beanFactory");}
}

在这里插入图片描述

12.FactoryBean

上面提到,我们可以通过BeanPostPorcessor来干涉Spring创建Bean的过程,但是如果我们想一个Bean完完全全由我们来创造,也是可以的,比如通过FactoryBean:

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;/*** @author Nickel* @version 1.0* @date 2023/7/7 0:56*/
@Component
public class NickelFactoryBean implements FactoryBean {@Overridepublic Object getObject() throws Exception {UserService userService = new UserService();return userService;}@Overridepublic Class<?> getObjectType() {return UserService.class;}
}

13.ExcludeFilter和IncludeFilter

ExcludeFilte让bean不被扫描到
配置之前
在这里插入图片描述
配置之后

package com.zhouyu;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.scheduling.annotation.EnableScheduling;import java.util.Collections;@ComponentScan("com.zhouyu")
@EnableScheduling
@PropertySource("classpath:spring.properties")
public class AppConfig {@Beanpublic ConversionServiceFactoryBean conversionService() {ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();conversionServiceFactoryBean.setConverters(Collections.singleton(new StringToUserConverter()));return conversionServiceFactoryBean;}
}

在这里插入图片描述
IncludeFilter不被扫描到
去掉UserService里面Component注解,配置之前
在这里插入图片描述

配置之后

package com.zhouyu;
import com.zhouyu.service.UserService;
import org.springframework.context.annotation.*;
import org.springframework.context.support.ConversionServiceFactoryBean;import java.util.Collections;@ComponentScan(value = "com.zhouyu",includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = UserService.class)})
public class AppConfig {@Beanpublic ConversionServiceFactoryBean conversionService() {ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();conversionServiceFactoryBean.setConverters(Collections.singleton(new StringToUserConverter()));return conversionServiceFactoryBean;}
}

在这里插入图片描述

14.MetadataReader、ClassMetadata、AnnotationMetadata

在Spring中需要去解析类的信息,比如类名、类中的方法、类上的注解,这些都可以称之为类的元数据,所以Spring中对类的元数据做了抽象,并提供了一些工具类。

MetadataReader表示类的元数据读取器,默认实现类为SimpleMetadataReader。比如:

package com.zhouyu;import com.zhouyu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;import java.io.IOException;public class Test {public static void main(String[] args) throws IOException {
//		ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class);
//		UserService userService =(UserService) context.getBean("userService");
//		System.out.println(userService);SimpleMetadataReaderFactory simpleMetadataReaderFactory = new SimpleMetadataReaderFactory();// 构造一个MetadataReaderMetadataReader metadataReader = simpleMetadataReaderFactory.getMetadataReader("com.zhouyu.service.UserService");// 得到一个ClassMetadata,并获取了类名ClassMetadata classMetadata = metadataReader.getClassMetadata();System.out.println(classMetadata.getClassName());// 获取一个AnnotationMetadata,并获取类上的注解信息AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();for (String annotationType : annotationMetadata.getAnnotationTypes()) {System.out.println(annotationType);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/13850.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

软负载Nginx详细配置及使用案例

Nginx使用与配置 什么是nginx Nginx 是一个高性能的HTTP和反向代理服务&#xff0c;也是一个IMAP/POP3/SMTP服务。 处理响应请求很快高并发连接低的内存消耗具有很高的可靠性高扩展性热部署 master 管理进程与 worker 工作进程的分离设计&#xff0c;使得 Nginx 具有热部署的…

Linux进程

目录 查看进程 进程状态 运行状态 睡眠状态 磁盘休眠状态 停止状态 死亡状态 僵死状态 孤儿进程 进程优先级 环境变量 PATH ​编辑 进程地址空间 进程创建 进程终止​​​​​​​ 进程等待 进程程序替换 简易shell实现 获取命令行 解析命令行 建立子进程…

应用层:客户-服务器方式(C/S)、对等方式(P2P)

1.应用层&#xff1a;客户-服务器方式和对等方式 笔记来源&#xff1a; 湖科大教书匠&#xff1a;客户-服务器方式和对等方式 声明&#xff1a;该学习笔记来自湖科大教书匠&#xff0c;笔记仅做学习参考 开发一种新的网络应用首先要考虑的问题就是网络应用程序在各种端系统上的…

权限管理系统后端实现1-SpringSecurity执行原理概述

spring security的简单原理&#xff1a; SpringSecurity有很多很多的拦截器&#xff0c;在执行流程里面主要有两个核心的拦截器 1&#xff0c;登陆验证拦截器AuthenticationProcessingFilter 2&#xff0c;资源管理拦截器AbstractSecurityInterceptor 但拦截器里面的实现需要…

基于YOLO的3D人脸关键点检测方案

目录 前言一、任务列表二、3D人脸关键点数据H3WB2.下载方法3.任务4.评估5.使用许可 3DFAWAFLW2000-3D 三、3D关键点的Z维度信息1.基于3DMM模型的方法2.H3WB 四、当前SOTA的方法1.方法1 五、我们的解决方法1.数据转为YOLO格式2.修改YOLO8Pose的入口出口3.开始训练&#xff0c;并…

网络的构成要素【图解TCP/IP(笔记七)】

文章目录 网络的构成要素通信媒介与数据链路网卡中继器网桥/2层交换机路由器/3层交换机4&#xff5e;7层交换机网关各种设备及其对应网络分层概览 网络的构成要素 通信媒介与数据链路 计算机之间通过电缆相互连接。电缆可以分为很多种&#xff0c;包括双绞线电缆、光纤电缆、同…

Openlayers实战:drawstart,drawend 绘制交互应用示例

Openlayers地图中,绘制一个多边形是非常见的一个应用,涉及到交互会在绘制开始 drawstart 和绘制结束drawend时,通常会在绘制完成后取消继续绘制,然后提出feature的一些信息。 效果图 源代码 /* * @Author: 大剑师兰特(xiaozhuanlan),还是大剑师兰特(CSDN) * @此源代…

机器学习基础之《特征工程(1)—数据集》

一、数据集 1、目标 知道数据集分为训练集和测试集 会使用sklearn的数据集 2、可用数据集 公司内部&#xff0c;比如百度、微博 数据接口&#xff0c;花钱 政府拥有的数据集 3、在学习阶段用到的数据集 scikit-learn特点&#xff1a; &#xff08;1&#xff09;数据量较小 &…

创建数据库Market、Team,按要求完成指定操作

创建数据库Market&#xff0c;在Market中创建数据表customers&#xff0c;customers表结构如表4.6所示&#xff0c;按要求进行操作。 代码如下&#xff1a; #(1&#xff09;创建数据库Market mysql> create database Market; Query OK, 1 row affected (0.00 sec)mysql>…

瓴羊QuickBI数据门户帮助企业高效管理和展示数据,使其更加明确易懂

随着信息技术时代的到来&#xff0c;越来越多的企业意识到商业信息是其最宝贵的资产之一。对于获取商业信息&#xff0c;需要专业的数据分析。因此&#xff0c;商业智能BI工具&#xff0c;如瓴羊QuickBI已经成为企业信息化中必不可少的工具。它拥有卓越的数据管理和展示功能&am…

【STM32智能车】小车状态

【STM32智能车】小车状态 搭建智能车 65MM轮径小车所选材料安装说明直行测试智能车可能存在的状态 智能车功能丰富&#xff0c;我们从最基础的开始&#xff0c;先来搭建一个智能车吧~。 搭建智能车 我们之前用了一个测试板子去学习调试电机&#xff0c;是时候拼装一个简单的车来…

学校公寓管理系统/基于微信小程序的学校公寓管理系统

摘 要 社会的发展和科学技术的进步&#xff0c;互联网技术越来越受欢迎。手机也逐渐受到广大人民群众的喜爱&#xff0c;也逐渐进入了每个学生的使用。手机具有便利性&#xff0c;速度快&#xff0c;效率高&#xff0c;成本低等优点。 因此&#xff0c;构建符合自己要求的操作…