02. Interpretation of Spring's underlying core concepts
AD |
BeanDefinitionBeanDefinitonBeanBeanDefinitionBeanclassBeanscopeBeanBeanlazylnitBeanintMethodNameBeandestroyMethodNameBean.
BeanDefinition
BeanDefinitonBeanBeanDefinitionBean
- classBean
- scopeBeanBean
- lazylnitBean
- intMethodNameBean
- destroyMethodNameBean
- ....... spring
SpringBean
- <bean/>
- @Bean
- @Component(@Service,@Controller)
Bean
BeanBeanDefinition
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);// BeanDefinitionbeanClassUser.classApplicationContextAbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefintion();context.registerBeanDefinition("user", beanDefinition);System.out.println(context.getBean("user"));
BeanDefinitionBean
beanDefinition.setScope("prototype"); // beanDefinition.setInitMethodName("init"); // beanDefinition.setLazyInit(true); //
<bean/>@Bean@ComponentBeanSpringBeanDefinitionSpring
BeanDefinitionReader
SpringBeanDefinitionBeanDefinitionReaderBeanDefinitionReaderSpringSpringSpring
AnnotatedBeanDefinitionReader
BeanDefinition
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);AnnotatedBeanDefinitionReader annotatedBeanDefinitionReader = new AnnotatedBeanDefinitionReader(context);// User.classBeanDefinitionannotatedBeanDefinitionReader.register(User.class);System.out.println(context.getBean("user"));
@Conditional@Scope@Lazy@Primary@DependsOn@Role@Description
XmlBeanDefinitionReader
<bean/>
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(context);int i = xmlBeanDefinitionReader.loadBeanDefinitions("spring.xml");System.out.println(context.getBean("user"));
ClassPathBeanDefinitionScanner
ClassPathBeanDefinitionScannerBeanDefinitionReader@ComponentBeanDefinition
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();context.refresh();ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);scanner.scan("com.zhouyu");System.out.println(context.getBean("userService"));
BeanFactory
BeanFactoryBeanBeanFactoryBeanBeanAPI
ApplicationContextBeanFactorySpring
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver { ...}
JavaApplicationContextListableBeanFactoryHierarchicalBeanFactoryListableBeanFactoryHierarchicalBeanFactoryBeanFactoryApplicationContextBeanFactoryApplicationContextBeanFactoryBeanFactoryApplicationContextBeanFactoryApplicationContextApplicationContextMessageSourceApplicationEventPublisherEnvironmentCapableApplicationContext
SpringnewApplicationContextnewBeanFactoryApplicationContextgetBean()BeanFactorygetBean()
SpringBeanFactory**
DefaultListableBeanFactory**
DefaultListableBeanFactoryApplicationContext
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();beanDefinition.setBeanClass(User.class);beanFactory.registerBeanDefinition("user", beanDefinition);System.out.println(beanFactory.getBean("user"));
DefaultListableBeanFactory
DefaultListableBeanFactory
- AliasRegistry
- BeanDefinitionRegistryBeanDefinition
- BeanFactoryBeanbeanBean
- SingletonBeanRegistryBean
- SimpleAliasRegistryAliasRegistry
- ListableBeanFactoryBeanFactoryBeanDefinitionbeanNamesbeanNames{Bean}
- HierarchicalBeanFactoryBeanFactoryBeanFactory
- DefaultSingletonBeanRegistrySingletonBeanRegistryBean
- ConfigurableBeanFactoryHierarchicalBeanFactorySingletonBeanRegistryBeanFactorySpring ELBeanFactoryELBeanFactoryBeanPostProcessorBeanFactoryBeanBeanDefinitionBean
- FactoryBeanRegistrySupportFactoryBean
- AutowireCapableBeanFactoryBeanFactoryBeanFactoryBeanBean
- AbstractBeanFactoryConfigurableBeanFactoryFactoryBeanRegistrySupportBeanFactorybeanNames
- ConfigurableListableBeanFactoryListableBeanFactoryAutowireCapableBeanFactoryConfigurableBeanFactory
- AbstractAutowireCapableBeanFactoryAbstractBeanFactoryAutowireCapableBeanFactory
- DefaultListableBeanFactoryAbstractAutowireCapableBeanFactoryConfigurableListableBeanFactoryBeanDefinitionRegistryDefaultListableBeanFactory
ApplicationContext
ApplicationContextBeanFactoryBeanFactory
- HierarchicalBeanFactoryBeanFactory
- ListableBeanFactorybeanNames
- ResourcePatternResolver
- EnvironmentCapable
- ApplicationEventPublisher
- MessageSource
ApplicationContext
- AnnotationConfigApplicationContext
- ClassPathXmlApplicationContext
AnnotationConfigApplicationContext
- ConfigurableApplicationContextApplicationContextBeanFactoryPostProcessorEnvironmentConfigurableListableBeanFactory
- AbstractApplicationContextConfigurableApplicationContext
- GenericApplicationContextAbstractApplicationContextBeanDefinitionRegistryApplicationContextBeanDefinition(DefaultListableBeanFactory beanFactory)
- AnnotationConfigRegistryBeanDefinition**@Configuration****@Bean**
- AnnotationConfigApplicationContextGenericApplicationContextAnnotationConfigRegistry
ClassPathXmlApplicationContext
AbstractApplicationContext
AnnotationConfigApplicationContext
AnnotationConfigApplicationContextBeanDefinition
MessageSource:
@Beanpublic MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource;}
BeanMessageSourceApplicationContext
context.getMessage("test", null, new Locale("en_CN"))
ApplicationContextApplicationContext
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Resource resource = context.getResource("file:/home/IdeaProjects/spring-framework/src/main/java/com/eemp/entity/User.java");System.out.println(resource.contentLength());
ApplicationContext
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Resource resource = context.getResource("file:/home/IdeaProjects/spring-framework/src/main/java/com/eemp/entity/UserService.java");System.out.println(resource.contentLength());System.out.println(resource.getFilename());Resource resource1 = context.getResource("https://www.baidu.com");System.out.println(resource1.contentLength());System.out.println(resource1.getURL());Resource resource2 = context.getResource("classpath:spring.xml");System.out.println(resource2.contentLength());System.out.println(resource2.getURL());
Resource[] resources = context.getResources("classpath:com/eemp/*.class");for (Resource resource : resources) { System.out.println(resource.contentLength()); System.out.println(resource.getFilename());}
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("eemp"));
@PropertySource("classpath:spring.properties")
properties.
@Beanpublic ApplicationListener applicationListener() { return new ApplicationListener() { @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println(""); } };}
context.publishEvent("kkk");
SpringStringSpring
PropertyEditor
JDK
public class StringToUserPropertyEditor extends PropertyEditorSupport implements PropertyEditor { @Override public void setAsText(String text) throws IllegalArgumentException { User user = new User(); user.setName(text); this.setValue(user); }}
StringToUserPropertyEditor propertyEditor = new StringToUserPropertyEditor();propertyEditor.setAsText("1");User value = (User) propertyEditor.getValue();System.out.println(value);
SpringPropertyEditor
@Beanpublic CustomEditorConfigurer customEditorConfigurer() { CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer(); Map<Class<?>, Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>(); // StringToUserPropertyEditorStringUserSpringStringUserPropertyEditor propertyEditorMap.put(User.class, StringToUserPropertyEditor.class); customEditorConfigurer.setCustomEditors(propertyEditorMap); return customEditorConfigurer;}
Bean:
@Componentpublic class UserService { @Value("xxx") private User user; public void test() { System.out.println(user); }}
test
OrderComparator
OrderComparatorSpring@OrderOrdered
public class A implements Ordered { @Override public int getOrder() { return 3; } @Override public String toString() { return this.getClass().getSimpleName(); }}
public class B implements Ordered { @Override public int getOrder() { return 2; } @Override public String toString() { return this.getClass().getSimpleName(); }}
public class Main { public static void main(String[] args) { A a = new A(); // order=3 B b = new B(); // order=2 OrderComparator comparator = new OrderComparator(); System.out.println(comparator.compare(a, b)); // 1 List list = new ArrayList<>(); list.add(a); list.add(b); // order list.sort(comparator); System.out.println(list); // BA }}
SpringOrderComparator
AnnotationAwareOrderComparator@Orderorder
@Order(3)public class A { @Override public String toString() { return this.getClass().getSimpleName(); }}@Order(2)public class B { @Override public String toString() { return this.getClass().getSimpleName(); }}public class Main { public static void main(String[] args) { A a = new A(); // order=3 B b = new B(); // order=2 AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator(); System.out.println(comparator.compare(a, b)); // 1 List list = new ArrayList<>(); list.add(a); list.add(b); // order list.sort(comparator); System.out.println(list); // BA }}
BeanPostProcessor
BeanPostProcessBenaBeanPostProcessorBeanPostProcessor
@Componentpublic class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if ("userService".equals(beanName)) { System.out.println(""); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if ("userService".equals(beanName)) { System.out.println(""); } return bean; }}
BeanPostProcessorBeanbeanNameBeanBean
BeanPostProcessorSpringBean
BeanFactoryPostProcessor
BeanFactoryPostProcessorBeanBeanPostProcessorBeanPostProcessorBeanBeanFactoryPostProcessorBeanFactoryBeanFactoryPostProcessor
@Componentpublic class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("beanFactory"); }}
postProcessBeanFactory()BeanFactory
FactoryBean
BeanPostPorcessorSpringBeanBeanFactoryBean
@Componentpublic class MyFactoryBean implements FactoryBean { @Override public Object getObject() throws Exception { UserService userService = new UserService(); return userService; } @Override public Class<?> getObjectType() { return UserService.class; }}
UserServiceBeanUserServiceBeanSpring
@BeanBeanFactoryBean@BeanBeanBean
ExcludeFilterIncludeFilter
FilterSpringExcludeFilterIncludeFilter
com.eempUserService@ComponentBean
@ComponentScan(value = "com.eemp", excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = UserService.class)})public class AppConfig {}
UserService@ComponentBean
@ComponentScan(value = "com.eemp", includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = UserService.class)})public class AppConfig {}
FilterType
- ANNOTATION
- ASSIGNABLE_TYPE
- ASPECTJAspectj
- REGEX
- CUSTOM
SpringAnnotationTypeFilterincludeFiltersSpring@ComponentBean
MetadataReaderClassMetadataAnnotationMetadata
SpringSpring
MetadataReaderSimpleMetadataReader
public class Test { public static void main(String[] args) throws IOException { SimpleMetadataReaderFactory simpleMetadataReaderFactory = new SimpleMetadataReaderFactory(); // MetadataReader MetadataReader metadataReader = simpleMetadataReaderFactory.getMetadataReader("com.eemp.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); } }}
SimpleMetadataReaderASM
ASMSpringSpringJVMASM
Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:[email protected])
Mobile advertising space rental |
Tag: Interpretation of Spring underlying core concepts
Still struggling? A clear understanding of the difference between C language and C++language in one article
NextThe 2022 Nobel Prize in Physics actually proves that our universe is not real?
Guess you like
-
China Leads in Developing IEC 63206 International Standard, Driving Global Innovation in Industrial Process Control System RecordersDetail
2025-01-18 11:06:14 1
-
The 2024 Micro-Short Series Industry Ecological Insight Report: 647,000 Job Opportunities, Rise of Diversified Business Models, and High-Quality Content as the Future TrendDetail
2025-01-17 17:33:01 1
-
Global PC Market Shows Moderate Recovery in 2024: High AIPC Prices a Bottleneck, Huge Growth Potential in 2025Detail
2025-01-17 11:02:09 1
-
Bosch's Smart Cockpit Platform Surpasses 2 Million Units Shipped, Showcasing Strength in Intelligent Driving TechnologyDetail
2025-01-17 10:55:29 1
-
YY Guangzhou Awarded "2024 Network Information Security Support Unit" for Outstanding ContributionsDetail
2025-01-17 10:43:28 1
-
TikTok CEO Invited to Trump's Inauguration, Biden Administration May Delay BanDetail
2025-01-16 20:06:11 1
-
Douyin Denies Opening International Registration: Overseas IPs Don't Equate to Overseas Registration; Platform Actively Combats Account ImpersonationDetail
2025-01-16 14:26:12 1
-
Lei Jun, Xiaomi's founder, chairman, and CEO, has set a new goal: learning to drive a forklift!Detail
2025-01-15 10:22:30 11
-
ByteDance Scholarship 2024: Fifteen Outstanding Doctoral Students Awarded RMB 100,000 Each to Advance Frontier Technology ExplorationDetail
2025-01-14 15:56:39 1
-
Fliggy Launches "Peace of Mind for the New Year" Service Initiative to Ensure Smooth Travel During the Year of the Snake Spring Festival RushDetail
2025-01-14 15:24:53 1
-
Arm's Massive Fee Hike and Potential In-House Chip Development: A Precursor to a Seismic Shift in the Chip Industry?Detail
2025-01-14 11:02:36 1
-
Adobe Firefly Launches: Generative AI Suite Revolutionizes Image and Video Processing EfficiencyDetail
2025-01-14 10:46:39 1
-
Chinese New Year Elements Sell Like Hotcakes Overseas: Cross-border E-commerce "Spring Festival Economy" Booms, Cainiao Overseas Warehouses Help Merchants Capture Market ShareDetail
2025-01-13 14:17:50 1
-
China Railway's 12306 System Successfully Navigates Spring Festival Travel RushDetail
2025-01-13 12:56:54 1
-
Handan, Hebei Province Successfully Tests First Low-Altitude Drone Delivery Route, Ushering in a New Era of Smart LogisticsDetail
2025-01-13 12:50:13 1
-
Kuaishou Leads in Developing Anti-Fraud Industry Standards, Contributing to a Secure and Reliable Short-Video CommunityDetail
2025-01-13 09:47:32 11
-
Microsoft Offers Top Salaries to Retain AI Talent: AI Software Engineers Earn Over $400,000 AnnuallyDetail
2025-01-12 17:28:34 11
- Detail
-
Chang'e-5 Mission Unveils Secrets: New Discoveries Regarding Lunar Magnetic Field Strength and Deep Dynamics 2 Billion Years AgoDetail
2025-01-10 11:42:44 11
-
SenseTime's "Day Day New" Multimodal Large Model: Native Fusion Enables Diverse ApplicationsDetail
2025-01-10 11:40:40 21