?先对自定义类使用@MyComponet的注解,在设置这个@MyComponet的的属性(一个
@interface接口),然后,扫描(BaseClassScanUtils.java执行,这文件不重要)当前包下是否有这个注解的类,再用MyComponentBeanFactoryPostProcessor.java(后工厂处理器)执行就行了
MyComponentBeanFactoryPostProcessor.java如下:
package com.itheima.processor;
import com.itheima.utils.BaseClassScanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import java.util.Map;
public class MyComponentBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
//通过扫描工具去扫描指定包及其子包下的所有类,收集使用@Mycomponent的注解的类
Map<String, Class> myComponentAnnotationMap = BaseClassScanUtils.scanMyComponentAnnotation("com.itheima");
//遍历Map,组装BeanDefinition进行注册
myComponentAnnotationMap.forEach((beanName,clazz)->{
//获得beanClassName
String beanClassName = clazz.getName();//com.itheima.beans.OtherBean
//创建BeanDefinition
BeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClassName(beanClassName);
//注册
registry.registerBeanDefinition(beanName,beanDefinition);
});
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
?
还要在主配置文件里配置
<bean class="com.itheima.processor.MyComponentBeanFactoryPostProcessor"></bean>