Is this a technical Spring term? Or is stereotype just used in a general sense?
I think Spring borrow the term Stereotype from the real world to Spring's technical term.
From American English dictionary:
(noun) a widely held but fixed and oversimplified image or idea of a particular type of person or thing.
In real world we know some stereotype, for example: American like to drink coffee. British like to drink tea. Of course, its not true for all American or British. Its just an oversimplification of American or British people.
Using stereotype help us making faster decision. When your American friends comes over, instead of asking them "What would you like to drink?" and wait for their response. You can assume that they want a coffee.
In Spring, stereotype help us to simplify object creation. You don't need to define the relationship between Type
, because you make stereotype of the Type
.
Note: Type
in Java. Class is a Type
.
Say we have these classes:
public abstract class Friend {
public abstract String favoriteDrink();
}
public class American extends Friend {
@Override
public String favoriteDrink() {
return "Coffee";
}
}
Without Stereotype
You have to define the relationship between Friend and American (Friend is-an American) in a Configuration.
@Configuration
public class YourAppConfig {
@Bean
public Friend defineFriend() {
return new American();
}
}
So, in the test you can verify that:
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourAppTest {
@Autowired
private Friend friend;
@Test
public void drinkTest() {
assertEquals(friend.favoriteDrink(), "Coffee");
}
}
With Stereotype
Stereotype tell Spring that all Friend is an American, directly on the Class declaration.
@Component
public class American extends Friend {
@Override
public String favoriteDrink() {
return "Coffee";
}
}
If your classes encounter a Friend class, it will assume its an American. It's a one-to-one relationship between Friend and American.
This is very useful if you want your class to behave that way. You don't need to define a Bean to your Configuration file. (You don't even need a Configuration file). Spring will automatically create a Bean from that Stereotype.
That is why the Component, Repository, Service, and Controller annotations belong to Stereotype package.
Spring doesn't care much about the detail of your class, from Spring perspective your Classes are either Repository
, Service
, and Controller
, if it doesn't belong to any of that, then its a Component
.
Spring just making oversimplification of your Classes. Hence, the name Stereotype.