Home > Software design >  Wrong profile is active
Wrong profile is active

Time:10-17

@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!";
    }
}

application.properties

spring.profiles.active=dog 

Result

--- The Best Pet is ---
Cats Are the Best!

I have come to my wit's end why cats are here. I can even comment the properties out, but cats are still here.

I would like to see dogs.

Gould you help me?

CodePudding user response:

It looks like the DogService is not a bean. So in the end you only have a single bean (CatService) and this one will be picked all the time.

CodePudding user response:

  1. You shoud to define a bean of DogPetService with @service.

  2. You shoud to add the cat profile to CatPetService. Like this :

    @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!";
        }
    }
    
  • Related