Spring Core - Different Types of Bean Injection
1. Overview
Dependency Injection is a very common technique in software engineering whereby an object supplies the dependencies of another object. Means that DI is about passing a dependency object to another a dependent object.Assume we have a client and a service that would be used by the client. We pass the service to the client rather than allowing the client to build it. DI is commonly related to a wide known taxonomy which is Inversion of control aka IoC. But simply, IoC is a more general than the DI. IoC means letting the other code call you rather than insisting od doing the calling.
All of this is managed through the Spring Container which requires some sort of configurations that are presented through XML-based configuration or Annotation-based configuration. We will focus on the Annotation-based one in the below subjects.
2. Maven Configuration
We need to make sure that Spring core and JUnited dependencies exists in our pom.xml
<properties>
<!-- Spring -->
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<!-- Test -->
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
3. Project Structure
Let's assume we have a requirement for building a notification service that's responsible for sending different notifications through different services like Email or SMS. Hence we will have a NotificationService class that's composed of some other services like EmailService and SMSService.
3.1. Classes Implementation
Message.java represents the model for an object that will be passed to whether the constructor or the setter method during the injection.public class Message {
private String body;
private String from;
private String to;
public void setBody(String body) {
this.body = body;
}
public String getBody() {
return body;
}
public void setFrom(String from) {
this.from = from;
}
public String getFrom() {
return from;
}
public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
}
MessageService.java is the interface to unify the contract for two services that will create. It contains only one method signature that will be implemented later.public interface MessageService {
void sendMessage();
Message getMessage();
}
We will create two beans each with unique names emailService and smsService that we will use for injection through the AppConfig class.import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.spring.core.di")
public class AppConfig {
@Bean
@Qualifier("emailMessage")
public Message emailMessage() {
Message emailMessage = new Message();
emailMessage.setBody("email message body");
emailMessage.setFrom("user1");
emailMessage.setTo("user2");
return emailMessage;
}
@Bean
@Qualifier("smsMessage")
public Message smsMessage() {
Message smsMessage = new Message();
smsMessage.setBody("sms message body");
smsMessage.setFrom("user2");
smsMessage.setTo("user1");
return smsMessage;
}
}
4. Dependency Injection Types
Now let's talk precisely about the DI in Spring that exists in two major types: Constructor-based and Setter-based.4.1. Constructor-based
This is achieved by invoking the constructor arguments and passing the relative arguments objects to it which we already call dependencies. Let's see how we achieve so in our example. We create a dependency for the model object Message in the AppConfig.java class configurations and set the values for its properties. We will actually create two dependencies for this dependency model.The class EmailServiceBean.java is the first implementation of the MessageService interface. So it implements the the sendMessage() and prints to the console the values of the Message object. As you can see there are no setter method for the object of Message rather than that we have one a constructor that we will depend on for the constructor injection.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("emailService")
public class EmailServiceBean implements MessageService {
private Message message;
@Autowired
public EmailServiceBean(Message emailMessage) {
this.message = emailMessage;
}
public void sendMessage() {
System.out.println("sending email message");
System.out.println("from: " + this.message.getFrom());
System.out.println("to: " + this.message.getTo());
System.out.println("body: " + this.message.getBody());
}
public Message getMessage() {
return message;
}
}
4.2. Setter-based
On the other hand, Setter-based injection is achieved by calling a setter method in our bean which will be SMSServiceBean that has composition of also the Message model. So the Spring container injects the other reference of the Message dependency with name equals smsMessage that's why we user the @Qualifier annotation above the setMessage method.SMSServiceBean.java is another implementation for the interface MessageService. This one is similar to the EmailServiceBean but it contains a setter method for the Message object. This method is annotated with @Autowired to point out that the Message object will be injected through the Spring container as a setter-based injection.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("smsService")
public class SMSServiceBean implements MessageService {
private Message message;
public void sendMessage() {
System.out.println("sending sms message");
System.out.println("from: " + this.message.getFrom());
System.out.println("to: " + this.message.getTo());
System.out.println("body: " + this.message.getBody());
}
@Autowired
@Qualifier("smsMessage")
public void setMessage(Message message) {
this.message = message;
}
public Message getMessage() {
return message;
}
}
5. Running the Example
Now, we reach out the class Application.java that contains the main method. It should look like so:import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
EmailServiceBean emailServiceBean = (EmailServiceBean) context.getBean("emailService");
emailServiceBean.sendMessage();
System.out.println();
SMSServiceBean smsServiceBean = (SMSServiceBean) context.getBean("smsService");
smsServiceBean.sendMessage();
}
}
We can also use the JUnit case ApplicationTest.java for initiating the Spring container and testing both services (EmailServiceBean and SMSServiceBean).import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.core.di.service.MessageService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
public class ApplicationTest {
@Autowired
@Qualifier("emailService")
MessageService emailServiceBean;
@Autowired
@Qualifier("smsService")
MessageService smsServiceBean;
@Test
public void testSendEmailMessage() {
smsServiceBean.sendMessage();
assertEquals(emailServiceBean.getMessage().getBody(), "email message body");
assertEquals(emailServiceBean.getMessage().getFrom(), "user1");
assertEquals(emailServiceBean.getMessage().getTo(), "user2");
}
@Test
public void testSendSMSMessage() {
smsServiceBean.sendMessage();
assertEquals(smsServiceBean.getMessage().getBody(), "sms message body");
assertEquals(smsServiceBean.getMessage().getFrom(), "user2");
assertEquals(smsServiceBean.getMessage().getTo(), "user1");
}
}
Running both classes will create the below output:sending email message
from: user1
to: user2
body: email message body
sending sms message
from: user2
to: user1
body: sms message body
6. Conclusion
When to use what?. Actually we can mix using both but Spring encourages using the constructor-based injection for the mandatory dependencies and the setter-based injection in the optional ones.Despite of we can use @Required annotation on the setter method to make the property a mandatory dependency. Also, it's recommended to use the constructor-based to implement application components as immutable objects and to ensure that required dependencies are not null.Now that we went through the basics of the injection types in Spring. I urge to get your hands and try running that examples and explore more annotations and configurations that can be applied. Happy coding :)
It was really an interesting blog, Thank you for providing unknown facts.
ReplyDeleteAviation Academy in Chennai
Air hostess training in Chennai
Airport management courses in Chennai
Ground staff training in Chennai
Aviation Courses in Chennai
air hostess institute in Chennai
airline and airport management courses in Chennai
airport ground staff training courses in Chennai
The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.
DeleteSpring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai
Great job. Keep updating this article by posting new informations.
ReplyDeleteSpoken English Classes in Chennai
English Coaching Classes in Chennai
IELTS Coaching in OMR
TOEFL Coaching Centres in Chennai
french classes
pearson vue
Spoken English Classes in OMR
Spoken English Classes in Porur
ReplyDeleteI like to learn a piece of new information about technology. Im really like your post. Good job.
Struts Training in Chennai
Best Struts Training institute in Chennai
Best Struts Training in Chennai
struts Training in Porur
Wordpress Training in Chennai
Wordpress Training
Spring Training in Chennai
Hibernate Training in Chennai
The article is very interesting and very understood to be read, may be useful for the people. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it. I have to bookmarked to check out new stuff on your post. Thanks for sharing the information keep updating, looking forward for more posts..
ReplyDeleteKindly visit us @
Madurai Travels
Best Travels in Madurai
Cabs in Madurai
Tours and Travels in Madurai
Wow, what an awesome spot to spend hours and hours! It's beautiful and I'm also surprised that you had it all to yourselves! we are the one of the best HIV treatment hospital in India..Click here for more details Best HIV Treatment in India | Top HIV Hospital in India | HIV AIDS Treatment in Mumbai | HIV Specialist in Bangalore | HIV Positive Treatment in India | Medicine for AIDS in India
ReplyDeleteExcellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up! Kindly visit us @
ReplyDeleteChristmas Gift Boxes | Wallet Box
Perfume Box Manufacturer | Candle Packaging Boxes | Luxury Leather Box | Luxury Clothes Box | Luxury Cosmetics Box
Shoe Box Manufacturer | Luxury Watch Box
Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing. For better education and future visit here 100% Job Placement | Best Colleges for Computer Engineering
ReplyDeleteBiomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu
Biotechnology Colleges in Coimbatore | Biotechnology Courses in Coimbatore
Best MCA Colleges in Tamilnadu | Best MBA Colleges in Coimbatore
Engineering Courses in Tamilnadu | Engg Colleges in Coimbatore
I really enjoyed your blog Thanks for sharing such an informative post.Looking For Some More Stuff.
ReplyDeleteshuttering works
I really enjoyed your blog Thanks for sharing such an informative post.Looking For Some More Stuff.
ReplyDeletebest seo company in bangalore SSS digital Marketing
Nice Post...I have learn some new information.thanks for sharing.
ReplyDeleteData Science Courses in Bangalore | Data Science training | Best Data Science institute in Bangalore
A very inspiring blog your article is so convincing that I never stop myself to say something about it. You’re doing a great job,Keep it up.
ReplyDelete100% Job Placement Tamilnadu | Best Colleges for Computer Engineering
Biomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu
"Biotechnology colleges in coimbatore, Biotechnology colleges in tamilnadu "
Biotechnology Courses in Coimbatore | Best MCA Colleges in Tamilnadu
Best MBA Colleges in Coimbatore | Engineering Courses in Tamilnadu
Engg Colleges in Coimbatore
Attend The Data Analytics Course in Bangalore From ExcelR. Practical Data Analytics Course in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Course in Bangalore.
ReplyDeleteExcelR Data Analytics Course in Bangalore
Wonderful post, This article have helped greatly continue writing ..
ReplyDeleteThanks for sharing information. I really appreciate it.
ReplyDeleteGreat Article
ReplyDeleteFinal Year Project Domains for CSE
Final Year Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai
Very nice post. iPhone Service Center in Chennai | Lenovo Mobile Service Center in Chennai
ReplyDeleteAttend The Analytics Training Institute From ExcelR. Practical Analytics Training Institute Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Analytics Training Institute.
ReplyDeleteExcelR Analytics Training Institute
Thanks for sharing...
ReplyDeleteVery good Keep it up.
Attend The PMP Certification From ExcelR. Practical PMP Certification Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The PMP Certification.
ReplyDeleteExcelR PMP Certification
Attend The Data Analytics Course From ExcelR. Practical Data Analytics Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Course.
ReplyDeleteExcelR Data Analytics Course
After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
ReplyDeleteExcelR data analytics courses
Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
ReplyDelete
ReplyDeleteA very inspiring blog your article is so convincing that I never stop myself to say something about it.
Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
ReplyDeletedata science course in mumbai
I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!
ReplyDeletedata science course in mumbai
I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
ReplyDeletedata analytics courses
Great Article
ReplyDeleteData Mining Projects
Python Training in Chennai
Project Centers in Chennai
Python Training in Chennai
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
ReplyDeletedata analytics courses
A very interesting blog....
ReplyDeleteKeep sharing the post like this.
ReplyDeleteIt’s so knowledgeable Nice blog...
ReplyDeleteNice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
ReplyDeleteKeep sharing the post like this.
ReplyDeleteThanks for sharing such a great blog
ReplyDeleteThanks for posting such a great blog
ReplyDeleteVermicompost Manufacturers | Vermicompost in chennai
Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
ReplyDeleteTours and Travels in Madurai | Best tour operators in Madurai
Best travel agency in Madurai | Best Travels in Madurai
Hi, Very nice article. I hope you will publish again such type of post. Thank you!
ReplyDeleteCorporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | Corporate gifts wholesale Singapore
ReplyDeleteThanks for sharing such a great blog
Vermicompost manufacturers in Tamilnadu | Vermicompost in Tamilnadu
Vermicompost Manufacturers | Vermicompost Suppliers
Vermicompost in Coimbatore | Vermicompost manufacturers in Chennai
Vermicompost in chennai | Best Vermicompost in chennai
.
Nice informative blog, it shares more intresting information. This blog is useful to me.
ReplyDeletegerman classes in bangalore
german language course in bangalore
german language classes in bangalore
german classes in marathahalli
best german classes in chennai
german language coaching centres in coimbatore
german classes in madurai
german language in hyderabad
Data Science Courses in Bangalore
AWS Training in Bangalore
ReplyDeleteHi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | Corporate gifts wholesale Singapore
It's very useful blog post with inforamtive and insightful content and i had good experience with this information. We, at the CRS info solutions ,help candidates in acquiring certificates, master interview questions, and prepare brilliant resumes.Find top Salesforce admin interview questions in 2020.
ReplyDeleteThese Salesforce developer interview questions are highly helpful in 2020. You can read these Salesforce lightning interview questions and Salesforce integration interview questions which are prepared by industry experts.
Thanks for sharing such a great blog
ReplyDeleteVermicompost manufacturers in Tamilnadu | Vermicompost in Tamilnadu
Vermicompost Manufacturers | Vermicompost Suppliers
Vermicompost in Coimbatore | Vermicompost manufacturers in Chennai
Vermicompost in chennai | Best Vermicompost in chennai
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.
ReplyDeleteData Science In Banglore With Placements
Data Science Course In Bangalore
Data Science Training In Bangalore
Best Data Science Courses In Bangalore
Data Science Institute In Bangalore
Thank you..
Thanks for sharing such a great blog
ReplyDeleteVermicompost manufacturers in Tamilnadu | Vermicompost in Tamilnadu
Vermicompost Manufacturers | Vermicompost Suppliers
Vermicompost in Coimbatore | Vermicompost manufacturers in Chennai
Vermicompost in chennai | Best Vermicompost in chennai
Hi, Very nice article. I hope you will publish again such type of post. Thank you!
ReplyDeleteCorporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | Corporate gifts wholesale Singapore
Business card holder singapore | T shirts supplier singapore
Thumb drive supplier singapore | Leather corporate gifts singapore
The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.
ReplyDeleteProjects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.
Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.
ReplyDeleteHi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | corporate gifts supplier
This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data scientist courses
ReplyDeleteVery nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data science course in Hyderabad
ReplyDeleteVery nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data science course in Hyderabad
ReplyDeleteExcellent post. I learned a lot from this blog and I suggest my friends to visit your blog to learn new concept about technology.Best data science courses in hyerabad
ReplyDeleteExcellent post. I learned a lot from this blog and I suggest my friends to visit your blog to learn new concept about technology.Best data science courses in hyerabad
ReplyDeleteAmazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
ReplyDeleteSimple Linear Regression
Correlation vs covariance
data science interview questions
KNN Algorithm
Logistic Regression explained
ReplyDeleteHi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | corporate gifts supplier
Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data science training in Hyderabad
ReplyDelete
ReplyDeleteThanks for sharing this information. I really appreciate it.
Iphone service center in tnagar | Iphone service center in chennai
Lenovo mobile service center in Tnagar | Lenovo Mobile service center in chennai
Moto service center in t nagar | Motorola service center in t nagar
Moto Service Center in Chennai | Motorola Service Center in chennai
I curious more interest in some of them hope you will give more information on this topics in your next articles.
ReplyDeletedata science training in Hyderabad
Thanks for sharing amazing blog. I am really happy to read your blog. Thanks for sharing your blog.
ReplyDeleteAndroid Training in Tambaram
Android Training in Anna Nagar
Android Training in Velachery
Android Training in T Nagar
Android Training in Porur
Android Training in OMR
Thanks for sharing these useful information! This is really interesting information for me.
ReplyDeleteSeo Services in Delhi, Best SEO Company in Delhi NCR, Best SEO Agency Delhi
This is a fabulous article, please try to give more useful information.
ReplyDeletelist to string python
what is data structure in python
what is polymorphism in oops with example
numpy example in python
python interview questions and answers pdf
types of data structure in python
New site is solid. A debt of gratitude is in order for the colossal exertion. ExcelR Business Analytics Courses
ReplyDeleteI really appreciate your work which you have shared here about the clothes. The article you have shared here is very informative and the points you have mentioned are very helpful. Thank you so much.Buy Latest Design Womens Hoodie Online
ReplyDeleteI am very thankful to you for posting such a great post about Fashion . The post is really helpful for me. Thanks for sharing it. Buy Online Luxury Clothes for Men
ReplyDeleteTo be honest your article is informative and very helpful. Hp Laptop
ReplyDeleteHp Laptop online
Great job for publishing such a pleasant article. Your article isn’t only useful but it's additionally really informative. many thanks because you've got been willing to share information with us.Buy Latest Design Mens Belts Online
ReplyDelete