Spring Framework Component Injection

Spring

Pada tulisan sebelumnya kita sudah membuat component dalam Spring. Pada tulisan ini kita akan mencoba melakukan Component Injection.

Membuat Class Component

Kita akan membuat 2 buah class Component

File : HelloComponentB.java

package com.timposu.belajarspring.belajarspring.component;

import org.springframework.stereotype.Component;

@Component
public class HelloComponentB {

	public String sayMessage(String message) {
		return message;
	}
}

File : HelloComponentA.java

package com.timposu.belajarspring.belajarspring.component;

import org.springframework.stereotype.Component;

@Component
public class HelloComponentA {

	private HelloComponentB componentB;

	public HelloComponentA(HelloComponentB componentB) {
		this.componentB = componentB;
	}

	public void sayMessage() {
		System.out.println(componentB.sayMessage("No Smoking"));
	}
}

SpringConfiguration class

Load component tadi melalui class configuation dengan menggunakan Annotation @ComponentScan

File : SpringConfiguration.java

package com.timposu.belajarspring.belajarspring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan("com.timposu.belajarspring.belajarspring")
public class SpringConfiguration {

}

Class Context

Panggil class Configuration dengan AnnotationConfigApplicationContext

File App.java

package com.timposu.belajarspring.belajarspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.timposu.belajarspring.belajarspring.component.HelloComponentA;

public class App
{
    public static void main( String[] args )
    {
    	 ApplicationContext context =
         		new AnnotationConfigApplicationContext(SpringConfiguration.class);

    	 HelloComponentA helloComponentA = context.getBean(HelloComponentA.class);
    	 helloComponentA.sayMessage();
     }
}

Run

No Smoking

Download

Download Download : BelajarSpringJavaConfig.zip

Video


Related Post