Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Spring framework does not allow autowire primitive types?

As per spring documentation it has been mentioned

it is by design

I want to understand the possible thinking behind this design.

like image 414
Sajal Chakraborty Avatar asked Dec 30 '15 10:12

Sajal Chakraborty


People also ask

Can we use @autowired in spring?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.

Can I Autowire in pojo?

The @Autowired annotation in spring automatically injects the dependent beans into the associated references of a POJO class. This annotation will inject the dependent beans by matching the data-type (i.e. Works internally as Autowiring byType).

Should I use primitive or wrapper?

Verdict. Generally, choose primitive types over wrapper classes unless using a wrapper class is necessary. Primitive Types will never be slower than Wrapper Objects, however Wrapper Objects have the advantage of being able to be null.

What is the default type of Autowire in spring?

The default mode of Spring's traditional XML-based configuration is 'no' i.e no auto wiring is enabled by default. But, if you choose to use annotation-based configuration(<context:annotation-config>), & for instance, if you are using @Autowired , then the default method of auto wiring for this is "byType".


1 Answers

It's because Autowiring is just an alternative for referencing your existing beans in ApplicationContext. It expects a bean or a class, primitive is not a class and it differs from Object. Which is why you can't Autowire primitive types. You can use wrapper classes of the primitive types such as Integer, Double etc... to be able to use Autowiring for such types because you are now referring to a class.

like image 166
Ruelos Joel Avatar answered Sep 25 '22 13:09

Ruelos Joel