@@ -15,6 +15,12 @@ | |||
</properties> | |||
<dependencies> | |||
<!-- https://mvnrepository.com/artifact/org.springframework/spring --> | |||
<dependency> | |||
<groupId>org.springframework</groupId> | |||
<artifactId>spring-context</artifactId> | |||
<version>5.2.13.RELEASE</version> | |||
</dependency> | |||
<dependency> | |||
<groupId>org.junit.jupiter</groupId> | |||
<artifactId>junit-jupiter</artifactId> |
@@ -1,21 +1,17 @@ | |||
package be.syntra; | |||
import be.syntra.common.AppConfig; | |||
import be.syntra.cowsay.*; | |||
import org.springframework.context.annotation.AnnotationConfigApplicationContext; | |||
import java.util.Scanner; | |||
public class App { | |||
public static void main(String[] args) { | |||
/** | |||
* Dependency Injection is a technique of creating software in which objects do not create their dependencies on itself. | |||
* instead objects declare dependencies that they need and it an external object or framework to provide | |||
* concrete dependencies to objects | |||
*/ | |||
CowSay cowSay = new DragonCowSay(); | |||
QuoteDao quoteDao = new QuoteDaoMysql(); | |||
cowSay.setQuoteDao(quoteDao); | |||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); | |||
CowSay cowSay = context.getBean("cowSay", CowSay.class); | |||
cowSay.showQuote(); | |||
Scanner in = new Scanner(System.in); | |||
@@ -32,5 +28,6 @@ public class App { | |||
System.out.println("Please enter y/n"); | |||
} | |||
} | |||
context.close(); | |||
} | |||
} |
@@ -0,0 +1,4 @@ | |||
package be.syntra; | |||
public class ApplicationContext { | |||
} |
@@ -0,0 +1,25 @@ | |||
package be.syntra.common; | |||
import be.syntra.cowsay.CowSay; | |||
import be.syntra.cowsay.OriginalCowSay; | |||
import be.syntra.cowsay.QuoteDao; | |||
import be.syntra.cowsay.QuoteDaoDummy; | |||
import org.springframework.context.annotation.Bean; | |||
import org.springframework.context.annotation.Configuration; | |||
@Configuration | |||
public class AppConfig { | |||
//define bean for Dao | |||
@Bean | |||
public QuoteDao quoteDao() { //-> the method name is the "Bean id" | |||
return new QuoteDaoDummy(); | |||
} | |||
//define Bean for swim coach AND dependency injection | |||
@Bean | |||
public CowSay cowSay() { //-> the method name is the "Bean id" | |||
return new OriginalCowSay(quoteDao()); | |||
} | |||
} |
@@ -4,6 +4,5 @@ public interface CowSay { | |||
void showQuote(); | |||
void voteUp(); | |||
void voteDown(); | |||
void setQuoteDao(QuoteDao quoteDao); | |||
} | |||
@@ -5,10 +5,11 @@ public class OriginalCowSay implements CowSay { | |||
QuoteDao quoteDao; | |||
Quote quote; | |||
public void setQuoteDao(QuoteDao quoteDao) { | |||
public OriginalCowSay(QuoteDao quoteDao) { | |||
this.quoteDao = quoteDao; | |||
} | |||
@Override | |||
public void showQuote() { | |||
quote = quoteDao.getRandomQuote(); |