RELnemtzov
RELnemtzov

Reputation: 81

In Spring, how do I create a POJO with a default value from configuration?

I am using the Spring framework to with a properties file that has the key:

empty.value = -

I would like to be able to create a POJO that would have that empty value as its default value for the default constructor of the POJO. Something like this:

public class Dog {

    private String name;

    public Dog(){
    }

    public Dog(String name){
        this.name = name;
    }
}

So that if Dog d = new Dog() is called, d.name will be - from the empty.value key.

Autowiring the name variable will just be null because Spring isn't aware of the POJO as well as using @Value("${empty.value}").

What would be the best way of achieving this?

Edit: To clarify, there are meant to be many Dogs throughout the system and I need to be able to initialize them on request.

Edit 2: Consider the following use case- I have an interface containing a method:

Dog transform(List<String> animals);

I would like to be able to know that whatever Dog is returned from the transform method has either - (configurable) as a name or a different value passed in to the constructor when created (or setter, later). I would like to ensure that for whatever transform does in any implementation, even if it fails, I will have a valid Dog with a name as mentioned.

Upvotes: 0

Views: 4323

Answers (1)

Andr&#233;s Oviedo
Andr&#233;s Oviedo

Reputation: 1428

If you are using the Spring framework, you have to create all your Spring beans using also Spring. For example:

Dog d = (Dog)context.getBean("dog");

Doing Dog d = new Dog() is a valid instance, but that way it's not processed by Spring.

Update about the Edit 2

If you want to ensure you always have a valid dog instance when calling the transform method, you can use a try catch block in the caller code. For example:

// caller class
Dog dog = null;
try{
   dog = yourInterface.transform(animals);
   if (dog == null || !validName(dog.name)){
       throw new RuntimeException("Not a valid dog/name");   
   }
}catch(Exception ex){
   dog = (Dog)context.getBean("dog");
}

Upvotes: 2

Related Questions