Constructor-based Dependency Injection by R4R Team

Constructor-based Dependency Injection:-
We can inject the dependency by constructor. The subelement of is used for constructor injection. Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to a static factory method similarly.

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

1 Create a project with a name SpringExample and create a package com.r4r.in under the src folder in the created project.
2 Add required Spring libraries using Add External JARs .
3 Create Java classes Test, Message and MainApp under the com.r4r.in.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
 

1 Create Test.java file.

package com.r4r.in;

public class Test {

private Message msg;

public Test(Message msg) {

System.out.println("Inside constructor Message." );

this.msg = msg;

}

public void show() {

msg.showmsg();

} }

2 Create another dependent class file Message.java.

package com.r4r.in;

public class Message {

public Message(){

System.out.println("Inside Message constructor." );

} public void showmsg() {

System.out.println("Inside showmsg." );

} }

3 Create MainApp.java file.

package com.r4r.in;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

Test t = (Test) context.getBean("test");

t.show();

} }

4 Following is the configuration file Beans.xml which has configuration for the constructor-based injection:

version="1.0" encoding="UTF-8"?>

"http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

"test" class="com.r4r.in.Test">

"test"/>

"msg" class="com.r4r.in.Message">

5 Run the Application .if everything is ok then show the message.

Inside Message constructor.

Inside constructor Message.

Inside showmsg.

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!