Home > Software design >  the `Company` class depends on `Address`, how do I describe such dependency?
the `Company` class depends on `Address`, how do I describe such dependency?

Time:05-28

I'm learning spring boot and trying to figure out how should I describe the dependency.

I'm aware that dependency injection is one of the core features of Spring framework.

How should I describe dependency in coding?

For example, I have two classes, Company and Address

@Entity
public class Address {
  @Id 
  @GeneratedValue
  private int id;
  private String street;
  private int number;
}

the Company class depends on Address, how do I describe such dependency?

should I go with addressId

@Entity
public class Company {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  private int addressId;
}

or the Address object itself

@Entity
public class Company {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  private Address address;
}

CodePudding user response:

You use the object. By adding a @JoinColumn you can specify what field on that object you are using as reference.

@Entity
public class Company {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  @OneToOne
  @JoinColumn(name="id")
  private Address address;
}

Note that this is not at all an example of dependency injection. Dependency injection is the concept where your class only knows it requires a type of functionality, and is being provided an implementation of it without having to know of that implementation. In Srping that is generally done by autowiring in some interface and providing the implementation as a Spring bean. This is done by using the @Autowire annotation which can be omitted when the field being wired in is final and a constructor is provided, for what is called constructor injection.

* As an analogy, consider a construction worker asking his pupil to hand him a thing to drill a hole into the wall. He is not concerned with it being a 'Bosch' or that it is a 400watt drill. He just cares that it drills holes.

CodePudding user response:

Since you are working with Pojos there is no need of thinking in terms of dependency because those models will not be dependent on any component from the spring container (atleast for your case). You can think of dependency injection when there is a need of single common object/component for your class.

So answer to you question is,you need to go with the second approach. You need to go with the address object itself.

Please see the documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction

  • Related