当前位置:首页 > Java 框架原理百科 > 正文

Java优学网Spring Bean配置教程:从XML到注解,轻松掌握依赖注入与Bean生命周期管理

@Service public class OrderService {

private final PaymentService paymentService;
private final InventoryService inventoryService;

@Autowired
public OrderService(PaymentService paymentService, InventoryService inventoryService) {
    this.paymentService = paymentService;
    this.inventoryService = inventoryService;
}

}

@Configuration public class DataSourceConfig {

@Bean
@Conditional(DevEnvironmentCondition.class)
public DataSource devDataSource() {
    return new EmbeddedDatabaseBuilder()
        .setType(EmbeddedDatabaseType.H2)
        .build();
}

@Bean
@Conditional(ProdEnvironmentCondition.class)
public DataSource prodDataSource() {
    return new MysqlDataSource();
}

}

@Component @Scope("prototype") public class PrototypeService {

// 每次获取都是新实例

}

@Service public class UserService {

@Autowired
private PrototypeService prototypeService;  // 这里实际上只注入了一次

}

Java优学网Spring Bean配置教程:从XML到注解,轻松掌握依赖注入与Bean生命周期管理

你可能想看:

相关文章:

文章已关闭评论!