Inject bean according to the environment

I'm developping spring-boot application that manage users. In User class I have Address that not have the same mapping in test environment and prod environment.

This is User class:

    public class User{
        private String name;
        private Address address

        // Getters and setters

This is address class

public class Address{

    private String city;
    private String county;

     private String appCode;

    // Getters and setters

My problem is that in production environment appCode is "custom_7876" and in tests environmentis "custom_9982" and there is another fields that has different mapping between tests and production environnement.

Would you have an idea how I can inject different Address according to the environment?

My idea was to declare Address like "Object" then if the environment= test I cast to AddressTests if not I cast it to AddressProd. But I don't know how

Would you have any suggestion?

Best regards

1 answer

  • answered 2017-06-17 19:13 sbjavateam

    You can use condition or profile annotation but only if it' a bean and lifecycle is managed by spring container.

    public class Address extends JsonSerializer<YourPojo> {
        private String appCode;
        public void serialize(Address pojo, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            jgen.writeStringField(appCode, pojo.getAppCode());

    and add into your spring context managed ObjectMapper

    useful api JsonComponent and Provide an easy way to register JsonSerializer and JsonDeserializer beans