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/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);
		}

	}
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

open*w*r*t +dnspod ddns动态解析ipv6 远程控制移动内网路由器

1.修改openw*r*t web https管理端口为8443 修改ipv6 https 监听端口list listen_https [::]:8443 cd /etc/config/vi uhttpdvi /etc/config/uhttpdconfig uhttpd mainlist listen_http 0.0.0.0:80list listen_http [::]:80list listen_https 0.0.0.0:443list listen_https [:…

前端Vue一款基于canvas的精美商品海报生成组件 根据个性化数据生成商品海报图 长按保存图片

前端Vue一款基于canvas的精美商品海报生成组件 根据个性化数据生成商品海报图 长按保存图片&#xff0c;下载完整代码请访问uni-app插件市场地址&#xff1a;https://ext.dcloud.net.cn/plugin?id13326 效果图如下: # cc-beautyPoster #### 使用方法 使用方法 <!-- pos…

Java虚拟机(JVM)、垃圾回收器

一、Java简介 1、Java开发及运行版本 JRE(Java Runtime Environment&#xff0c;运行环境) 所有的程序都要在JRE下才能够运行。包括JVM和Java核心类库和支持文件。JDK(Java Development Kit&#xff0c;开发工具包) 用来编译、调试Java程序的开发工具包。包括Java工具(javac/…

【Redis】3、Redis 作为缓存(Redis中的穿透、雪崩、击穿、工具类)

目录 一、什么是缓存二、给业务添加缓存&#xff08;减少数据库访问次数&#xff09;三、给店铺类型查询业务添加缓存(1) 使用 String 类型(2) 使用 List 类型 四、缓存的更新策略(1) 主动更新(2) 最佳实现方案(3) 给查询商铺的缓存添加超时剔除和主动更新的策略① 存缓存&…

泰迪智能科技基于产业技能生态链学生学徒制的双创工作室--促进学生高质量就业

据悉&#xff0c;6月28日&#xff0c;广东省人力资源和社会保障厅在广东岭南现代技师学院举行广东省“产教评”技能生态链建设对接活动。该活动以“新培养、新就业、新动能”为主题&#xff0c;总结推广“产教评”技能人才培养新模式&#xff0c;推行“岗位培养”学徒就业新形式…

Tomcat多实例部署

1、关闭防火墙&#xff0c;将安装 Tomcat 所需软件包传到/opt目录下2、安装好 JDK3、设置JDK环境变量4、安装 tomcat5、配置 tomcat 环境变量6、修改 tomcat2 中的 server.xml 文件&#xff0c;要求各 tomcat 实例配置不能有重复的端口号7、修改各 tomcat 实例中的 startup.sh …

更便捷的人体三维模型制作方法

人体三维模型是一种以计算机辅助设计技术为基础的创新工具&#xff0c;它在医学、生物学、运动学等领域具有广泛的应用价值。这种模型通过将人体的形态、结构与功能等要素进行数字化处理和计算&#xff0c;能够以立体图像的形式展现出来。它可以精确地模拟人体的各种部位&#…

【C】数据在内存中的存储

前言 > 在内存中&#xff0c;整型和浮点型存储的方式是不同的&#xff0c;从内存中读取的方式也是有所差异的&#xff0c;这篇文章主要介绍整型和浮点型在内存中存储的方式。 整型在内存中的存储 计算机中有符号数有3种表示方式&#xff1a; 原码&#xff1a;直接将二进制按…

查看虚拟机主机IP

虚拟机主机ip 文章目录 ifconfigip addr图形化界面 ifconfig 失败了 ip addr 图形化界面

Windows远程连接linux中mysql数据库

我没有mysql并且没有把mysql配置到环境变量中&#xff0c;所以现在我要下载mysql 一.下载mysql Mysql官网下载地址&#xff1a;https://downloads.mysql.com/archives/installer 二.安装mysql 1. 选择设置类型 双击运行mysql-installer-community-8.0.26.msi&#xff0c;这…

MySQL简单查询操作

系列文章目录 前言SELECT子句SELECT后面之间跟列名DISTINCT,ALL列表达式列更名 WHERE子句WHERE子句中可以使用的查询条件比较运算特殊比较运算符BETWEEN...AND...集合查询&#xff1a;IN模糊查询&#xff1a;LIKE空值比较&#xff1a;IS NULL 多重条件查询 ORDER BY子句排序复杂…

【基于容器的部署、扩展和管理】3.10 云原生容器运行时环境和配置管理

往期回顾&#xff1a; 第一章&#xff1a;【云原生概念和技术】 第二章&#xff1a;【容器化应用程序设计和开发】 第三章&#xff1a;【3.1 容器编排系统和Kubernetes集群的构建】 第三章&#xff1a;【3.2 基于容器的应用程序部署和升级】 第三章&#xff1a;【3.3 自动…

Anaconda详细安装及配置教程(Windows)

Anaconda详细安装及配置教程&#xff08;Windows&#xff09; 一、下载方式1、官网下载2、网盘下载 二、安装三、配置四、创建虚拟环境 一、下载方式 1、官网下载 点击下载 点击window下载即可。 2、网盘下载 点击下载 二、安装 双击运行 点next 点I agree next 如…

专项练习21

目录 一、选择题 1、下列逻辑表达式的结果为false的是&#xff08;&#xff09; 2、请问以下JS代码输出的结果是什么&#xff1f; 3、以下哪些对象是Javascript内置的可迭代对象&#xff1f; 二、编程题 1、找到数组参数中的最大值并返回。注意&#xff1a;数组中只包含数字 …

OpenCV读取一张8位无符号四通道图像并显示

#include <iostream> #include <opencv2/imgcodecs.hpp> #include <opencv2/opencv.hpp> #include

GreenPlum分布式集群部署实战

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3; 哈喽&#xff01;大家好&#xff0c;我是【IT邦德】&#xff0c;江湖人称jeames007&#xff0c;10余年DBA及大数据工作经验 一位上进心十足的【大数据领域博主】&#xff01;&#x1f61c;&am…

Django实现简单的音乐播放器 3

在原有音乐播放器上请求方式优化和增加加载本地音乐功能。 效果&#xff1a; 目录 播放列表优化 设置csrf_token 前端改为post请求 视图端增加post验证 加载歌曲 视图 设置路由 模板 加载layui css 加载layui js 增加功能列表 功能列表脚本实现 最终效果 总结 播…

Vue 如何简单快速组件化

文章目录 前言相关文章组件化实战如何引入组件什么是父组件&#xff0c;什么是子组件如何实现给子组件赋值完整代码 如何调用子组件方法完整代码 总结 前言 为了简化拆分复杂的代码逻辑&#xff0c;和实现代码的组件化&#xff0c;封闭化。我们需要使用组件化的方法。我这里只…

SDN-OpenDaylight与Mininet的原理、安装、使用

一、前言 本文将介绍OpenDaylight与Mininet的原理并介绍他们的安装及简单的使用&#xff0c;本实验的环境为Liunx Ubuntu 16.04&#xff0c;已成功安装OVS&#xff0c;但没有安装Mininet。 二、原理 &#xff08;一&#xff09;OpenDaylight OpenDaylight是一个软件定义网络&…

天猫数据分析工具(天猫实时数据)

后疫情时代&#xff0c;聚会、聚餐与送礼热度上涨&#xff0c;酒类产品既作为送礼首选又作为佐餐饮品的热门选手也受此影响迎来消费小高峰。在此背景下&#xff0c;白酒市场也开始复苏并不断加快速度。 根据鲸参谋电商数据分析平台的相关数据显示&#xff0c;2023年1月份至4月…