Issue
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;
}
Solution
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
Answered By - HARI HARAN
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)