点此返回

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
public class AtBeanPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory
(ConfigurableListableBeanFactory configurableListableBeanFactory)
throws BeansException {
try {
//读取类信息
CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
MetadataReader reader = factory
.getMetadataReader(new ClassPathResource("com/itheima/a05/Config.class"));
//获取被@Bean标注的方法
//1.获取和注解相关的元数据
//2.进一步获取被@Bean注解标注的方法
Set<MethodMetadata> methods = reader
.getAnnotationMetadata()
.getAnnotatedMethods(Bean.class.getName());

for (MethodMetadata method : methods) {
System.out.println(method);
//解析@Bean注解中的属性
String initMethod = (String)
method.getAnnotationAttributes(Bean.class.getName()).get("initMethod");
//利用BeanDefinitionBuilder获取BeanDefinition,并加入bean工厂
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
builder.setFactoryMethodOnBean(method.getMethodName(),"config");
//指定自动装配模式(因为SqlSessionFactoryBean有一个dataSource参数)
builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
if (initMethod.length() > 0){
builder.setInitMethodName(initMethod);
}
AbstractBeanDefinition bd = builder.getBeanDefinition();
//注册Bean到容器中
if (configurableListableBeanFactory
instanceof DefaultListableBeanFactory beanFactory) {
beanFactory.registerBeanDefinition(method.getMethodName(),bd);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

当其他类调用时,只需调用容器的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);

//解析@Bean
context.registerBean(AtBeanPostProcessor.class);

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