简体   繁体   中英

When default constructor is required explicitly along with parameterized constructor

I am trying to learn spring dependency injection. I want to know when there is need of default constructor in dependency injection and what happen if we do not use default constructor explicitly

如果计划在不带任何参数的情况下实例化Bean,则必须提供一个默认的构造函数。

You should only provide a default constructor if there is a safe way to instantiate the bean that way - let the code document itself.

It is much better to include your bean's dependencies as constructor parameters, which allows you to make it very clear what your bean needs. The following is very clear:

@Autowired
public MyBean(WidgetService widgetService, NutService nutService, BoltService boltService) {

Whereas a default constructor for MyBean with the @Autowired annotation on various setters can get you into situations where the bean doesn't have all the dependencies it needs:

public MyBean() {

This is very useful when instantiating the bean manually, for example when testing the object.

Also, don't confuse the needs of Hibernate and other mapping solutions which tend to need a default constructor as well as a parameterised one, with other objects such as Spring Beans which don't. Mapping solutions tend to create an empty instance of the POJO (Plain Old Java Object) and then call setters to store values when unmarshalling from the database/XML/JSON/etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM