Constructor-based Dependency Injection:-
We can inject the dependency by constructor. The
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"?>
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">
5 Run the Application .if everything is ok then show the message.
Inside Message constructor.
Inside constructor Message.
Inside showmsg.