控制反轉 (Inversion of Control)**:對象創建與依賴管理從應用代碼移交給容器。配合 **DI (Dependency Injection)** 實現依賴注入。
ApplicationContext
public interface ApplicationContext {
Object getBean(String name);
Object getBean(String name, String className);
}
PropertiesReader
public class PropertiesReader {
private final String fileName;
public PropertiesReader(String fileName) { this.fileName = fileName; }
public Map<String, String> load() {
Properties props = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(fileName)) {
props.load(is);
} catch (IOException e) { throw new RuntimeException(e); }
Map<String, String> map = new HashMap<>();
for (String key : props.stringPropertyNames()) {
map.put(key, props.getProperty(key));
}
return map;
}
}
ClassPathXmlApplicationContext
public class ClassPathXmlApplicationContext implements ApplicationContext {
private final Map<String, String> beanMap;
public ClassPathXmlApplicationContext(String configFile) {
this.beanMap = new PropertiesReader(configFile).load();
}
@Override
public Object getBean(String name) {
String className = beanMap.get(name);
if (className == null) throw new IllegalArgumentException("No bean: " + name);
try {
System.err.println("創建 Bean: " + name + " -> " + className);
return Class.forName(className).getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Bean 實例化失敗: " + name, e);
}
}
@Override public Object getBean(String name, String className) { return null; }
}
applicationContext.properties
student=com.example.Student
service=com.example.UserService
dao=com.example.UserDao
public class IoCTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.properties");
Student s = (Student) ctx.getBean("student");
s.setSid("15301");
s.setSname("張三");
System.out.println(s.getSid() + " " + s.getSname());
}
}
beanName → 全限定類名Class.forName().newInstance() 實例化 (需無參構造)BeanDefinition 元數據、BeanPostProcessor 擴展點、循環依賴檢測、AOP 代理創建InitializingBean, DisposableBean)