@SpringBootApplication
public class SfgDiApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SfgDiApplication.class, args);
PetController petController = ctx.getBean("petController", PetController.class);
System.out.println("--- The Best Pet is ---");
System.out.println(petController.whichPetIsTheBest());
}
@Controller
@ResponseBody
public class PetController {
public PetController(PetService petService) {
this.petService = petService;
}
private final PetService petService;
@GetMapping("pet-type")
public String whichPetIsTheBest(){
return petService.getPetType();
}
}
public interface PetService {
String getPetType();
}
@Service("cat")
public class CatPetService implements PetService {
@Override
public String getPetType() {
return "Cats Are the Best!";
}
}
@Profile({"dog", "default"})
public class DogPetService implements PetService {
public String getPetType(){
return "Dogs are the best!";
}
}
應用程式屬性
spring.profiles.active=dog
結果
--- The Best Pet is ---
Cats Are the Best!
我不明白為什么貓在這里。我什至可以將屬性注釋掉,但貓仍然在這里。我想看狗。
接下來我可以嘗試什么?
uj5u.com熱心網友回復:
看起來 DogService 不是 bean。所以最后你只有一個 bean (CatService),這個會一直被選中。
uj5u.com熱心網友回復:
我認為你可以像這樣實作你想要的:
@Configuration("petConfig")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PetConfig {
@Value("${spring.profiles.active}")
private String type;
@Bean(name = "petService")
@Primary
public PetService petService() {
PetService petService = null;
if ("cat".equals(type)) {
petService = new CatPetService();
}
if ("dog".equals(type)) {
petService = new DogPetService();
}
return petService;
}
}
使用@Service 注釋 CatPetService 和 DogPetService。通過這種方式,您可以輕松地調整代碼,而無需硬編碼和重復。
uj5u.com熱心網友回復:
您應該使用@service定義一個DogPetService bean。
您應該將貓組態檔添加到CatPetService。像這樣 :
@Service("cat") @Profile({"cat"}) public class CatPetService implements PetService { @Override public String getPetType() { return "Cats Are the Best!"; } } @Profile({"dog", "default"}) @Service("dog") public class DogPetService implements PetService { public String getPetType(){ return "Dogs are the best!"; } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516957.html
標籤:春天弹簧靴
