Search code examples
javaspringdependency-injectionconstructor-injection

how does a constructor-arg having value as String passed to the Constructor accepting Integer?


I'm building a Spring Application project, Which is using a Spring DI (constructor injection) to inject the objects. There is one Student class -

public class Student {
       private int id;

and having Constructor

public Student(int id)
{this.id = id; }

I'm injecting the objects using constructor injection like this ---

<constructor-arg name="id" value="1"/>

Now, here the value (1) is passed as String but the constructor is accepting int . I'm not able to figure out, how Spring is doing it. Is it just simple Type cast or something else?


Solution

  • Spring does this job , Below is the notes from spring document .

    Below is the text from spring documentation :

    4.Each property or constructor argument which is a value must be able to be converted from whatever format it was specified in, to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types, such as int, long, String, boolean, etc.