点此返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class MapperPostProcessor  implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry
(BeanDefinitionRegistry beanFactory)
throws BeansException {
try {
//扫描 mapper 包下的资源(使用通配符解析器)
PathMatchingResourcePatternResolver resolver =
new PathMatchingResourcePatternResolver();
Resource[] resources = resolver
.getResources("classpath:com/itheima/a05/mapper/**/*.class");

//创建名称生成器对象
AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();

//读取类的元数据信息
CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
for (Resource resource : resources) {
MetadataReader reader = factory.getMetadataReader(resource);
ClassMetadata classMetadata = reader.getClassMetadata();
//判断是否是接口
if (classMetadata.isInterface()) {
//生成 BeanDefinition
AbstractBeanDefinition bd1 =
BeanDefinitionBuilder
.genericBeanDefinition(MapperFactoryBean.class)
//给构造方法设置参数值(接口名称)
.addConstructorArgValue(classMetadata.getClassName())
//设置装配模式
.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE)
.getBeanDefinition();

//再生成一个 BeanDefinition
AbstractBeanDefinition bd2 =
BeanDefinitionBuilder
.genericBeanDefinition(classMetadata.getClassName())
.getBeanDefinition();
//根据bd2生成名称,以免覆盖bd1生成的名称
String beanName = generator.generateBeanName(bd2, beanFactory);

//注册到Bean工厂
beanFactory.registerBeanDefinition(beanName,bd1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void postProcessBeanFactory
(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
}
}

当其他类调用时,只需调用容器的registerBean方法,传入对实现类.class文件即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class BeanApp {
private static final Logger log = LoggerFactory.getLogger(BeanApp.class);
public static void main(String[] args) throws IOException {
//创建一个干净容器
GenericApplicationContext context = new GenericApplicationContext();
context.registerBean("config", Config.class);

//解析Mapper接口
context.registerBean(MapperPostProcessor.class);

//初始化容器
context.refresh();
for (String name : context.getBeanDefinitionNames()) {
System.out.println(name);
}
//销毁容器
context.close();
}
}