// 使用Spring框架的依赖注入(DI)来注入Bean。推荐的方式是使用构造器注入,因为它可以使类更易于测试,并确保所有必需的依赖项在创建对象时都已提供。
// 1. 定义一个接口及其实现类
public interface MyService {
void perform();
}
public class MyServiceImpl implements MyService {
@Override
public void perform() {
System.out.println("Performing service");
}
}
// 2. 使用构造器注入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
private final MyService myService;
// 构造器注入
@Autowired
public MyComponent(MyService myService) {
this.myService = myService;
}
public void doSomething() {
myService.perform();
}
}
// 3. 配置Spring应用上下文
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example") // 确保扫描到你的组件
public class AppConfig {
}
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyComponent myComponent = context.getBean(MyComponent.class);
myComponent.doSomething();
}
}
MyService 是一个接口,MyServiceImpl 是它的实现类。MyComponent 类中,通过构造器注入 MyService 的依赖。这种方式确保了在创建 MyComponent 实例时,所有的依赖项都已经准备好。AppConfig 类配置Spring应用上下文,并使用 @ComponentScan 注解扫描指定包中的组件。Main 类中,创建 ApplicationContext 并获取 MyComponent 实例,调用其方法以执行业务逻辑。这种方式不仅使代码更清晰,还提高了可测试性和维护性。
上一篇:java继承父类
下一篇:java密码加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站