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