Spring底层核心架构

news2024/11/16 5:59:22

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/beans
	   https://www.springframework.org/schema/beans/spring-beans.xsd
	   http://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);
		//是否包含bean
		System.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");
		//是否包含bean
		System.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 {
	@Bean
	public 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 {

	@Autowired
	private OrderService orderService;

	private ApplicationContext applicationContext;

	public void test(){
		System.out.println(applicationContext.getMessage("test", null, new Locale("de")));
	}


	@Override
	public 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 {

	@Autowired
	private OrderService orderService;

	private ApplicationContext applicationContext;


	public void test(){
		applicationContext.publishEvent("kkkk");
	}


	@Override
	public 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 {
	@Bean
	public ApplicationListener applicationListener() {
		return new ApplicationListener() {
			@Override
			public 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 {

	@Override
	public 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 {

	@Override
	public 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 {

	@Autowired
	private OrderService orderService;

	private ApplicationContext applicationContext;

	@Value("Nickel")
	private User user;


	public void test(){
		applicationContext.publishEvent("kkkk");
		System.out.println(user);
	}


	@Override
	public 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 {

	@Override
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
		return sourceType.getType().equals(String.class) && targetType.getType().equals(User.class);
	}

	@Override
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(String.class, User.class));
	}

	@Override
	public 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 {
	@Bean
	public 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 {

	@Autowired
	private OrderService orderService;

	private ApplicationContext applicationContext;

	@Value("Nickel")
	private User user;


	public void test(){
		applicationContext.publishEvent("kkkk");
		System.out.println(user);
	}


	@Override
	public 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 {

	@Override
	public int getOrder() {
		return 3;
	}

	@Override
	public 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 {
	@Override
	public int getOrder() {
		return 2;
	}

	@Override
	public 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=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);  // 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 {

	@Override
	public 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{

	@Override
	public 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=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); // 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 {

	@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;
	}
}

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 {
	@Override
	public 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 {

	@Override
	public Object getObject() throws Exception {
		UserService userService = new UserService();
		return userService;
	}

	@Override
	public 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 {
	@Bean
	public 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 {
	@Bean
	public 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();

		// 构造一个MetadataReader
		MetadataReader 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.coloradmin.cn/o/730882.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CASS扣除中间区域面积的方法

1、打开cass软件&#xff0c;绘制一个矩形和圆形&#xff0c;圆形全部位于矩形框内&#xff0c;具体如下&#xff1a; 2、点击“地物编辑”菜单栏下的“图案填充”&#xff0c;如下&#xff1a; 3、在命令行内输入实体填充、选择范围线方式填充&#xff0c;选择后可得到如下结果…

基于单片机的智能路灯控制系统人体感应灯光控制系统的设计与实现

功能介绍 以51单片机作为主控系统&#xff1b;LCD1602液晶显示当前时间、年月日、时分秒&#xff1b;按键看看有设置自动手动模式&#xff1b;3路红外探头用来感应当前3个区域是否有人&#xff1b;按键可以设置当前时间、开启和关闭教室灯光时间&#xff1b;在手动模式下&#…

debian to go

可以使用虚拟机操作&#xff0c;在运行镜像到安装步骤时选择 u盘 不需要手动分 /boot 分区之类的&#xff0c;“Automaction”自动分区就行&#xff0c;全安装到根目录。boot load 安装到 /dev/sdb&#xff0c;也就是硬盘本身 推荐使用gpt分区表&#xff0c;建议拿不用的盘练…

Basic of Solidity (solidity基础)

目录 1.first contract 申明编译器版本 定义合约 合约构造函数 定义变量 定义函数 2.data type 值类型&#xff08;Value Types&#xff09; 引用类型&#xff08;Reference Types&#xff09; 映射类型&#xff08;Mapping Types&#xff09; Solidity是一种用于编写…

vue + element 笔记(vue2.0)

1.安装nodejs&#xff0c;cmd中运行 node -v 验证是否成功 2.安装cnpm&#xff0c;cmd中运行 npm install -g cnpm --registryhttps://registry.npm.taobao.org&#xff0c;cmd中 cnpm -v 验证是否成功 3.安装vue-cli&#xff0c;cmd中运行 cnpm install --global vue-cli&…

三、Java的运算符

三、运算符 运算符是一种特殊的符号&#xff0c;用以表示数据的运算、赋值和比较等。 3.1、算术运算符 - * / % (前) (后) (前)-- (后)-- % :取余运算 结果的符号与被模数的符号相同 开发中&#xff0c;经常使用%来判断能否被除尽的情况 3.2、赋值运算符 注意&#xff1a;s2…

Spring Boot 中的 Native SQL 是什么, 如何使用

在 Spring Boot 中&#xff0c;我们通常使用 ORM 框架&#xff08;例如 Hibernate 或 MyBatis&#xff09;来操作数据库。但是&#xff0c;有时候我们需要执行一些自定义的 SQL 查询或更新语句&#xff0c;这时候就需要使用 Spring Boot 中的 Native SQL。 在本文中&#xff0…

Matlab绘图系列教程-Matlab 34 种绘图函数示例(下)

Matlab绘图系列教程&#xff1a;揭秘高质量科学图表的绘制与优化 文章目录 Matlab绘图系列教程&#xff1a;揭秘高质量科学图表的绘制与优化第一部分&#xff1a;入门指南1.1 简介关于本教程的目的与范围Matlab绘图在科学研究中的重要性 1.2 准备工作安装Matlab及其工具箱 1.3 …

8、添加PolylineCollection线

本节演示添加线要素&#xff0c;使用第四节单击事件的例子&#xff0c;修改点击事件创建线要素。 1、重新修改地图默认位置 double r glm::radians(-45.0); Cesium::HeadingPitchRoll *orientation new Cesium::HeadingPitchRoll(0.0, r, 0.0); glm::dvec3 initialPosition…

map和set的封装

目录 封装逻辑 用红黑树封装set和map 红黑树的定义改变 迭代器 红黑树的迭代器 set的迭代器 map重载[]操作的实现 比较关键——得到 key的类型K 封装逻辑 用红黑树封装set和map map和set用红黑树来实现的&#xff1b;红黑树的前三个模板参数分别表示&#xff1a;得到key的…

C语言---程序环境和预处理(底层原理万字详解)

文章目录 前言&#x1f31f;一、程序的翻译环境和执行环境&#x1f31f;二、详解编译链接&#x1f30f;2.1命令&#x1f30f;2.2 板书详解&#x1f30f;2.3运行环境 &#x1f31f;三、预处理详解&#x1f30f;3.1预定义符号&#x1f30f;3.2 #define&#x1f4ab;3.2.1 #define…

第三章 SSD存储介质:闪存

3.1 闪存物理结构 闪存芯片从小到大依此是由&#xff1a;cell&#xff08;单元&#xff09;、page&#xff08;页&#xff09;、block&#xff08;块&#xff09;、plane&#xff08;平面&#xff09;、die&#xff08;核心&#xff09;、NAND flash&#xff08;闪存芯片&#…

【动手学习深度学习--逐行代码解析合集】10Dropout暂退法

【动手学习深度学习】逐行代码解析合集 10Dropout暂退法 视频链接&#xff1a;动手学习深度学习–Dropout暂退法 课程主页&#xff1a;https://courses.d2l.ai/zh-v2/ 教材&#xff1a;https://zh-v2.d2l.ai/ 1、暂退法原理 2、从零开始实现暂退法 import torch from torch i…

微服务网关技术选型:Zuul2、Gateway、OpenResty、Kong

1、简介 当使用单体应用程序架构时&#xff0c;客户端&#xff08;Web 或移动端&#xff09;通过向后端应用程序发起一次 REST 调用来获取数据。负载均衡器将请求路由给 N 个相同的应用程序实例中的一个。然后应用程序会查询各种数据库表&#xff0c;并将响应返回给客户端。微…

missing-semester————1

文章目录 shell概述echoshell如何知道去哪寻找date或echo呢&#xff1f;$PATHlsman流根用户 shell概述 root1test:~$ $表示身份不是root用户 ~表示当前所在位置是"home" root1test:~$ date Sat Jul 8 02:57:44 UTC 2023输入命令&#xff0c;会被shell解析 上述执行…

静态路由配置——Cisco Packet Tracer

这里放一个用Packet Tracer 8.0实现的配置好的静态路由文件&#xff0c;配置如下 下载链接如下&#xff1a; https://wwix.lanzoue.com/ifp5T11ksnla

内嵌tomcat报错

严重: Unable to process Jar entry [module-info.class] from Jar [jar:file:/D:/javaTools/apache-maven-bin/apache-maven-3.6.1/maven-repo/com/fasterxml/jackson/core/jackson-databind/2.10.5/jackson-databind-2.10.5.jar!/] for annotations org.apache.tomcat.util.b…

NI采集卡USB-6361多通道模拟输入采集报错解决方案

文章目录 前言一、现有例程1、前面板2、程序框图 二、采集测试1、单通道采集2、多通道采集①、错误的做法②、正确的做法1&#xff09;前面板2&#xff09;程序框图3&#xff09;运行测试 总结 前言 折腾一块 USB-6361 采集卡很久了&#xff0c;之前都是单通道采集模拟信号&am…

云原生(第六篇)k8s-kubeadmin部署

master&#xff08;2C/4G&#xff0c;cpu核心数要求大于2&#xff09; 192.168.169.10 docker、kubeadm、kubelet、kubectl、flannel node01&#xff08;2C/2G&#xff09; 192.168.169.30 docker、kubeadm、kubelet、kubect…

汇总:FlatLaf-intellij-themes皮肤效果一览

关于主题包&#xff1a; FlatLaf 是一个跨平台的 Java Swing 外观库&#xff0c;提供现代化的平面化用户界面。 导包 <dependency><groupId>com.formdev</groupId><artifactId>flatlaf</artifactId><version>3.1.1</version><sco…