1. *由容器创建和管理* *bean**,**bean* *应当为容器内单实例* * 注册 bean 方法为 register 2. *根据类型* *getBean* 3. *bean* *有基本依赖注入功能,根据**类型**进行依赖注入* 完成后应该能实现如下功能 ```java static class A { @Autowired // 自定义 private B b; public void foo() { System.out.println("A foo()"); b.bar(); } } static class B { public void bar() { System.out.println("B bar()"); } } public static void main(String[] args) { BeanFactory container = new Container(); container.register(A.class); // 注册 A container.register(B.class); // 注册 B A a = container.getBean(A.class); // 获取 A 实例 container.autowired(a); // 依赖注入 a.foo(); // 不应该出现空指针,即 B 注入成功 } ```
时间: 2024-01-17 13:31:06 浏览: 64
SSH笔记-通过实现FactoryBean接口来创建 Bean
您可以使用以下代码来实现所需的功能:
```java
import java.util.HashMap;
import java.util.Map;
class Container implements BeanFactory {
private Map<Class<?>, Object> beanMap = new HashMap<>();
@Override
public void register(Class<?> clazz) {
try {
Object bean = clazz.getDeclaredConstructor().newInstance();
beanMap.put(clazz, bean);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public <T> T getBean(Class<T> clazz) {
return clazz.cast(beanMap.get(clazz));
}
@Override
public void autowired(Object bean) {
try {
for (var field : bean.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(Autowired.class)) {
field.setAccessible(true);
Class<?> fieldType = field.getType();
Object dependency = beanMap.get(fieldType);
field.set(bean, dependency);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
interface BeanFactory {
void register(Class<?> clazz);
<T> T getBean(Class<T> clazz);
void autowired(Object bean);
}
@interface Autowired {
}
static class A {
@Autowired
private B b;
public void foo() {
System.out.println("A foo()");
b.bar();
}
}
static class B {
public void bar() {
System.out.println("B bar()");
}
}
public static void main(String[] args) {
BeanFactory container = new Container();
container.register(A.class);
container.register(B.class);
A a = container.getBean(A.class);
container.autowired(a);
a.foo();
}
```
运行以上代码,输出应为:
```
A foo()
B bar()
```
阅读全文