在Java類中,實現類的依賴注入通常有以下幾種方法:
public class MyClass {
private MyDependency dependency;
public MyClass(MyDependency dependency) {
this.dependency = dependency;
}
}
public class MyClass {
private MyDependency dependency;
public void setDependency(MyDependency dependency) {
this.dependency = dependency;
}
}
public interface DependencyInjector {
void injectDependency(MyClass myClass);
}
public class MyDependencyInjector implements DependencyInjector {
@Override
public void injectDependency(MyClass myClass) {
myClass.setDependency(new MyDependency());
}
}
@Autowired
注解,由依賴注入框架負責注入依賴對象。public class MyClass {
@Autowired
private MyDependency dependency;
}
依賴注入框架如Spring、Guice等可以幫助實現依賴注入功能,通過配置文件或注解來管理類與依賴之間的關系。