Spring - Dependency Injection
If dependency injection is used then the class B is given to class A via:
Spring - Setter Injection Example
InjectSetter.java
package com.jtc;
public class InjectSetter {
private String message = null;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.jtc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestInjectSetter {
public static void main(String[] args) {
BeanFactory beanfactory = new ClassPathXmlApplicationContext("context.xml");
InjectSetter bean = (InjectSetter) beanfactory.getBean("welcome");
System.out.println(bean.getMessage());
}
}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <bean id="welcome" class="com.jtc.InjectSetter"> <property name="message" value="Setter Injection!"/> </bean> </beans>
InjectConstructor.java
package com.jtc;
public class InjectConstructor {
private String message = null;
public InjectConstructor(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
package com.jtc;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestInjectConstructor {
public static void main(String[] args) {
BeanFactory beanfactory = new ClassPathXmlApplicationContext("context.xml");
InjectConstructor bean = (InjectConstructor) beanfactory.getBean("welcome");
System.out.println(bean.getMessage());
}
}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <bean id="welcome" class="com.jtc.InjectConstructor"> <constructor-arg value="Constructor Injection!"/> </bean> </beans>
spring-aop-4.1.6.RELEASE
spring-aspects-4.1.6.RELEASE
spring-beans-4.1.6.RELEASE
spring-context-4.1.6.RELEASE
spring-context-support-4.1.6.RELEASE
spring-core-4.1.6.RELEASE
spring-expression-4.1.6.RELEASE
spring-instrument-4.1.6.RELEASE
spring-instrument-tomcat-4.1.6.RELEASE
spring-jdbc-4.1.6.RELEASE
spring-jms-4.1.6.RELEASE
spring-messaging-4.1.6.RELEASE
spring-orm-4.1.6.RELEASE
spring-oxm-4.1.6.RELEASE
spring-test-4.1.6.RELEASE
spring-tx-4.1.6.RELEASE
spring-web-4.1.6.RELEASE
spring-webmvc-4.1.6.RELEASE
spring-webmvc-portlet-4.1.6.RELEASE
spring-websocket-4.1.6.RELEASE
Constructor Injection!