生成简单的依赖注入实现IOC框架代码
时间: 2024-04-29 08:25:14 浏览: 69
依赖注入IOC
好的,以下是一个简单的依赖注入实现IOC框架代码示例:
```java
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("MyServiceImpl do something.");
}
}
public class MyController {
private MyService myService;
public void setMyService(MyService myService) {
this.myService = myService;
}
public void doSomething() {
myService.doSomething();
}
}
public class MyContainer {
private Map<Class, Object> beans = new HashMap<>();
public <T> T getBean(Class<T> clazz) throws Exception {
T bean = (T) beans.get(clazz);
if (bean == null) {
bean = clazz.newInstance();
beans.put(clazz, bean);
injectDependency(bean);
}
return bean;
}
private void injectDependency(Object bean) throws Exception {
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Autowired.class)) {
Object injectBean = getBean(field.getType());
field.setAccessible(true);
field.set(bean, injectBean);
}
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyContainer container = new MyContainer();
container.getBean(MyController.class).doSomething();
}
}
```
请问您还有其他问题吗?或者您需要我解释上面的代码吗?
阅读全文