在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等可以帮助实现依赖注入功能,通过配置文件或注解来管理类与依赖之间的关系。