JAVA-15787 Created new di-modules and server-modules
- Moved spring-freemarker to spring-web-modules
This commit is contained in:
9
di-modules/cdi/README.md
Normal file
9
di-modules/cdi/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
## CDI
|
||||
|
||||
This module contains articles about Contexts and Dependency Injection (CDI)
|
||||
|
||||
### Relevant Articles:
|
||||
- [CDI Interceptor vs Spring AspectJ](https://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
|
||||
- [An Introduction to CDI (Contexts and Dependency Injection) in Java](https://www.baeldung.com/java-ee-cdi)
|
||||
- [Introduction to the Event Notification Model in CDI 2.0](https://www.baeldung.com/cdi-event-notification)
|
||||
|
||||
51
di-modules/cdi/pom.xml
Normal file
51
di-modules/cdi/pom.xml
Normal file
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cdi</artifactId>
|
||||
<name>cdi</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>${cdi-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>${weld-se-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${aspectjweaver.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cdi-api.version>2.0.SP1</cdi-api.version>
|
||||
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
|
||||
<aspectjweaver.version>1.9.2</aspectjweaver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.cdi2observers.application;
|
||||
|
||||
import com.baeldung.cdi2observers.events.ExampleEvent;
|
||||
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
public class BootstrappingApplication {
|
||||
|
||||
public static void main(String... args) {
|
||||
SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = containerInitializer.initialize()) {
|
||||
container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.cdi2observers.events;
|
||||
|
||||
public class ExampleEvent {
|
||||
|
||||
private final String eventMessage;
|
||||
|
||||
public ExampleEvent(String eventMessage) {
|
||||
this.eventMessage = eventMessage;
|
||||
}
|
||||
|
||||
public String getEventMessage() {
|
||||
return eventMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.cdi2observers.events;
|
||||
|
||||
import javax.enterprise.event.Event;
|
||||
import javax.inject.Inject;
|
||||
|
||||
public class ExampleEventSource {
|
||||
|
||||
@Inject
|
||||
Event<ExampleEvent> exampleEvent;
|
||||
|
||||
public void fireEvent() {
|
||||
exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.cdi2observers.observers;
|
||||
|
||||
import com.baeldung.cdi2observers.events.ExampleEvent;
|
||||
|
||||
import javax.annotation.Priority;
|
||||
import javax.enterprise.event.Observes;
|
||||
|
||||
public class AnotherExampleEventObserver {
|
||||
|
||||
public String onEvent(@Observes @Priority(2) ExampleEvent event) {
|
||||
return event.getEventMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.cdi2observers.observers;
|
||||
|
||||
import com.baeldung.cdi2observers.events.ExampleEvent;
|
||||
import com.baeldung.cdi2observers.services.TextService;
|
||||
import javax.annotation.Priority;
|
||||
import javax.enterprise.event.Observes;
|
||||
|
||||
public class ExampleEventObserver {
|
||||
|
||||
public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
|
||||
return textService.parseText(event.getEventMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.cdi2observers.services;
|
||||
|
||||
public class TextService {
|
||||
|
||||
public String parseText(String text) {
|
||||
return text.toUpperCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.dependencyinjection.application;
|
||||
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
|
||||
public class FileApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
System.out.println(imageFileProcessor.openFile("file1.png"));
|
||||
System.out.println(imageFileProcessor.writeFile("file1.png"));
|
||||
System.out.println(imageFileProcessor.saveFile("file1.png"));
|
||||
container.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.dependencyinjection.factories;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import javax.enterprise.inject.Produces;
|
||||
|
||||
public class TimeLoggerFactory {
|
||||
|
||||
@Produces
|
||||
public TimeLogger getTimeLogger() {
|
||||
return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.GifFileEditorQualifier;
|
||||
|
||||
@GifFileEditorQualifier
|
||||
public class GifFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing GIF file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving GIF file " + fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
public interface ImageFileEditor {
|
||||
|
||||
String openFile(String fileName);
|
||||
|
||||
String editFile(String fileName);
|
||||
|
||||
String writeFile(String fileName);
|
||||
|
||||
String saveFile(String fileName);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.JpgFileEditorQualifier;
|
||||
|
||||
@JpgFileEditorQualifier
|
||||
public class JpgFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing JPG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving JPG file " + fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.dependencyinjection.imagefileeditors;
|
||||
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
|
||||
@PngFileEditorQualifier
|
||||
public class PngFileEditor implements ImageFileEditor {
|
||||
|
||||
@Override
|
||||
public String openFile(String fileName) {
|
||||
return "Opening PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String editFile(String fileName) {
|
||||
return "Editing PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String writeFile(String fileName) {
|
||||
return "Writing PNG file " + fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String saveFile(String fileName) {
|
||||
return "Saving PNG file " + fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.dependencyinjection.imageprocessors;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
import javax.inject.Inject;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.ImageFileEditor;
|
||||
|
||||
public class ImageFileProcessor {
|
||||
|
||||
private final ImageFileEditor imageFileEditor;
|
||||
private final TimeLogger timeLogger;
|
||||
|
||||
@Inject
|
||||
public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) {
|
||||
this.imageFileEditor = imageFileEditor;
|
||||
this.timeLogger = timeLogger;
|
||||
}
|
||||
|
||||
public ImageFileEditor getImageFileditor() {
|
||||
return imageFileEditor;
|
||||
}
|
||||
|
||||
public TimeLogger getTimeLogger() {
|
||||
return timeLogger;
|
||||
}
|
||||
|
||||
public String openFile(String fileName) {
|
||||
return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String editFile(String fileName) {
|
||||
return imageFileEditor.editFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String writeFile(String fileName) {
|
||||
return imageFileEditor.writeFile(fileName) + " at: " + timeLogger.getTime();
|
||||
}
|
||||
|
||||
public String saveFile(String fileName) {
|
||||
return imageFileEditor.saveFile(fileName)+ " at: " + timeLogger.getTime();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.dependencyinjection.loggers;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
|
||||
public class TimeLogger {
|
||||
|
||||
private final SimpleDateFormat dateFormat;
|
||||
private final Calendar calendar;
|
||||
|
||||
public TimeLogger(SimpleDateFormat dateFormat, Calendar calendar) {
|
||||
this.dateFormat = dateFormat;
|
||||
this.calendar = calendar;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return dateFormat.format(calendar.getTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface GifFileEditorQualifier {}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface JpgFileEditorQualifier {}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dependencyinjection.qualifiers;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import javax.inject.Qualifier;
|
||||
|
||||
@Qualifier
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
|
||||
public @interface PngFileEditorQualifier {}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.interceptor;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.interceptor.InterceptorBinding;
|
||||
|
||||
@InterceptorBinding
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Audited {
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.interceptor;
|
||||
|
||||
import javax.interceptor.AroundInvoke;
|
||||
import javax.interceptor.Interceptor;
|
||||
import javax.interceptor.InvocationContext;
|
||||
|
||||
@Audited
|
||||
@Interceptor
|
||||
public class AuditedInterceptor {
|
||||
public static boolean calledBefore = false;
|
||||
public static boolean calledAfter = false;
|
||||
|
||||
@AroundInvoke
|
||||
public Object auditMethod(InvocationContext ctx) throws Exception {
|
||||
calledBefore = true;
|
||||
Object result = ctx.proceed();
|
||||
calledAfter = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.interceptor.Audited;
|
||||
|
||||
public class SuperService {
|
||||
@Audited
|
||||
public String deliverService(String uid) {
|
||||
return uid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.spring.aspect;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@Aspect
|
||||
public class SpringTestAspect {
|
||||
@Autowired
|
||||
private List<String> accumulator;
|
||||
|
||||
@Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
|
||||
public Object auditMethod(ProceedingJoinPoint jp) throws Throwable {
|
||||
String methodName = jp.getSignature().getName();
|
||||
accumulator.add("Call to " + methodName);
|
||||
Object obj = jp.proceed();
|
||||
accumulator.add("Method called successfully: " + methodName);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.spring.configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
import com.baeldung.spring.aspect.SpringTestAspect;
|
||||
import com.baeldung.spring.service.SpringSuperService;
|
||||
|
||||
@Configuration
|
||||
@EnableAspectJAutoProxy
|
||||
public class AppConfig {
|
||||
@Bean
|
||||
public SpringSuperService springSuperService() {
|
||||
return new SpringSuperService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringTestAspect springTestAspect() {
|
||||
return new SpringTestAspect();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public List<String> getAccumulator() {
|
||||
return new ArrayList<String>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.spring.service;
|
||||
|
||||
public class SpringSuperService {
|
||||
public String getInfoFromService(String code) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
9
di-modules/cdi/src/main/resources/META-INF/beans.xml
Normal file
9
di-modules/cdi/src/main/resources/META-INF/beans.xml
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
|
||||
bean-discovery-mode="all">
|
||||
<interceptors>
|
||||
<class>com.baeldung.interceptor.AuditedInterceptor</class>
|
||||
</interceptors>
|
||||
</beans>
|
||||
13
di-modules/cdi/src/main/resources/logback.xml
Normal file
13
di-modules/cdi/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.interceptor.AuditedInterceptor;
|
||||
import com.baeldung.service.SuperService;
|
||||
|
||||
public class InterceptorIntegrationTest {
|
||||
Weld weld;
|
||||
WeldContainer container;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
weld = new Weld();
|
||||
container = weld.initialize();
|
||||
}
|
||||
|
||||
@After
|
||||
public void shutdown() {
|
||||
weld.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() {
|
||||
SuperService superService = container.select(SuperService.class).get();
|
||||
String code = "123456";
|
||||
superService.deliverService(code);
|
||||
|
||||
Assert.assertTrue(AuditedInterceptor.calledBefore);
|
||||
Assert.assertTrue(AuditedInterceptor.calledAfter);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.spring.configuration.AppConfig;
|
||||
import com.baeldung.spring.service.SpringSuperService;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = { AppConfig.class })
|
||||
public class SpringInterceptorIntegrationTest {
|
||||
@Autowired
|
||||
SpringSuperService springSuperService;
|
||||
|
||||
@Autowired
|
||||
private List<String> accumulator;
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenService_whenServiceAndAspectExecuted_thenOk() {
|
||||
String code = "123456";
|
||||
String result = springSuperService.getInfoFromService(code);
|
||||
|
||||
Assert.assertThat(accumulator.size(), is(2));
|
||||
Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
|
||||
Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.test.cdi2observers.tests;
|
||||
|
||||
import com.baeldung.cdi2observers.services.TextService;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class TextServiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTextServiceInstance_whenCalledparseText_thenCorrect() {
|
||||
TextService textService = new TextService();
|
||||
assertThat(textService.parseText("Baeldung")).isEqualTo("BAELDUNG");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GifFileEditorUnitTest {
|
||||
|
||||
private static GifFileEditor gifFileEditor;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setGifFileEditorInstance() {
|
||||
gifFileEditor = new GifFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorlInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.openFile("file1.gif")).isEqualTo("Opening GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.editFile("file1.gif")).isEqualTo("Editing GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.writeFile("file1.gif")).isEqualTo("Writing GIF file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGifFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(gifFileEditor.saveFile("file1.gif")).isEqualTo("Saving GIF file file1.gif");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
|
||||
public class ImageProcessorUnitTest {
|
||||
|
||||
private static ImageFileProcessor imageFileProcessor;
|
||||
|
||||
@BeforeClass
|
||||
public static void setImageProcessorInstance() {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class)
|
||||
.get();
|
||||
container.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
|
||||
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
|
||||
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String openFileLog = imageFileProcessor.openFile("file1.png");
|
||||
assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(openFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String editFileLog = imageFileProcessor.editFile("file1.png");
|
||||
assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(editFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String writeFileLog = imageFileProcessor.writeFile("file1.png");
|
||||
assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(writeFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String saveFileLog = imageFileProcessor.saveFile("file1.png");
|
||||
assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(saveFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
private LocalTime getLoggedTime(String log) throws ParseException {
|
||||
String logTimeString = log.split("at: ")[1];
|
||||
|
||||
int hour = Integer.valueOf(logTimeString.split(":")[0]);
|
||||
int minutes = Integer.valueOf(logTimeString.split(":")[1]);
|
||||
|
||||
LocalTime loggedTime = LocalTime.of(hour, minutes);
|
||||
return loggedTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JpgFileEditorUnitTest {
|
||||
|
||||
private static JpgFileEditor jpgFileUtil;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setJpgFileEditorInstance() {
|
||||
jpgFileUtil = new JpgFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.openFile("file1.jpg")).isEqualTo("Opening JPG file file1.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.editFile("file1.gif")).isEqualTo("Editing JPG file file1.gif");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.writeFile("file1.jpg")).isEqualTo("Writing JPG file file1.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpgFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(jpgFileUtil.saveFile("file1.jpg")).isEqualTo("Saving JPG file file1.jpg");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
@PngFileEditorQualifier
|
||||
public class PngFileEditorUnitTest {
|
||||
|
||||
private static PngFileEditor pngFileEditor;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setPngFileEditorInstance() {
|
||||
pngFileEditor = new PngFileEditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPngFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
assertThat(pngFileEditor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.factories.TimeLoggerFactory;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TimeLoggerFactoryUnitTest {
|
||||
@Test
|
||||
public void givenTimeLoggerFactory_whenCalledgetTimeLogger_thenOneAssertion() {
|
||||
TimeLoggerFactory timeLoggerFactory = new TimeLoggerFactory();
|
||||
assertThat(timeLoggerFactory.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TimeLoggerUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTimeLoggerInstance_whenCalledgetLogTime_thenOneAssertion() {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
TimeLogger timeLogger = new TimeLogger(dateFormat, calendar);
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(timeLogger.getTime()).isEqualTo(currentTime);
|
||||
}
|
||||
}
|
||||
7
di-modules/dagger/README.md
Normal file
7
di-modules/dagger/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Dagger
|
||||
|
||||
This module contains articles about Dagger
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Introduction to Dagger 2](https://www.baeldung.com/dagger-2)
|
||||
48
di-modules/dagger/pom.xml
Normal file
48
di-modules/dagger/pom.xml
Normal file
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>dagger</artifactId>
|
||||
<name>dagger</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>di-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Dagger 2 -->
|
||||
<dependency>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger</artifactId>
|
||||
<version>${dagger.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Annotation processor for Dagger 2 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger-compiler</artifactId>
|
||||
<version>${dagger.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<dagger.version>2.16</dagger.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
/**
|
||||
* Brand of a {@link Car}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Brand {
|
||||
|
||||
/**
|
||||
* The name of the brand.
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* Instantiates a new Brand.
|
||||
*
|
||||
* @param name
|
||||
* the {@link #name}
|
||||
*/
|
||||
public Brand(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #name}.
|
||||
*
|
||||
* @return the {@link #name}
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #name}.
|
||||
*
|
||||
* @param name
|
||||
* the new {@link #name}
|
||||
*/
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
/**
|
||||
* Represents a car.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Car {
|
||||
|
||||
/**
|
||||
* The car's engine.
|
||||
*/
|
||||
private Engine engine;
|
||||
|
||||
/**
|
||||
* The car's brand.
|
||||
*/
|
||||
private Brand brand;
|
||||
|
||||
/**
|
||||
* Instantiates a new Car.
|
||||
*
|
||||
* @param engine
|
||||
* the {@link #engine}
|
||||
* @param brand
|
||||
* the {@link #brand}
|
||||
*/
|
||||
@Inject
|
||||
public Car(Engine engine, Brand brand) {
|
||||
this.engine = engine;
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #engine}.
|
||||
*
|
||||
* @return the {@link #engine}
|
||||
*/
|
||||
public Engine getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #engine}.
|
||||
*
|
||||
* @param engine
|
||||
* the new {@link #engine}
|
||||
*/
|
||||
public void setEngine(Engine engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link #brand}.
|
||||
*
|
||||
* @return the {@link #brand}
|
||||
*/
|
||||
public Brand getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link #brand}.
|
||||
*
|
||||
* @param brand
|
||||
* the new {@link #brand}
|
||||
*/
|
||||
public void setBrand(Brand brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
/**
|
||||
* Engine of a {@link Car}.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class Engine {
|
||||
|
||||
/**
|
||||
* Starts the engine.
|
||||
*/
|
||||
public void start() {
|
||||
System.out.println("Engine started");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the engine.
|
||||
*/
|
||||
public void stop() {
|
||||
System.out.println("Engine stopped");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import dagger.Component;
|
||||
|
||||
/**
|
||||
* Dagger component for building vehicles.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
@Singleton
|
||||
@Component(modules = VehiclesModule.class)
|
||||
public interface VehiclesComponent {
|
||||
|
||||
/**
|
||||
* Builds a {@link Car}.
|
||||
*
|
||||
* @return a {@link Car}
|
||||
*/
|
||||
public Car buildCar();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
|
||||
/**
|
||||
* Dagger module for providing vehicles components.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
@Module
|
||||
public class VehiclesModule {
|
||||
|
||||
/**
|
||||
* Creates an {@link Engine}.
|
||||
*
|
||||
* @return an {@link Engine}
|
||||
*/
|
||||
@Provides
|
||||
public Engine provideEngine() {
|
||||
return new Engine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link Brand}.
|
||||
*
|
||||
* @return a {@link Brand}
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
public Brand provideBrand() {
|
||||
return new Brand("Baeldung");
|
||||
}
|
||||
}
|
||||
13
di-modules/dagger/src/main/resources/logback.xml
Normal file
13
di-modules/dagger/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.dagger.intro;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for building a {@link Car} using Dagger.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class DaggerUnitTest {
|
||||
|
||||
/**
|
||||
* Builds two {@link Car} and checks that the fields are injected correctly.
|
||||
*/
|
||||
@Test
|
||||
public void givenGeneratedComponent_whenBuildingCar_thenDependenciesInjected() {
|
||||
VehiclesComponent component = DaggerVehiclesComponent.create();
|
||||
|
||||
Car carOne = component.buildCar();
|
||||
Car carTwo = component.buildCar();
|
||||
|
||||
Assert.assertNotNull(carOne);
|
||||
Assert.assertNotNull(carTwo);
|
||||
Assert.assertNotNull(carOne.getEngine());
|
||||
Assert.assertNotNull(carTwo.getEngine());
|
||||
Assert.assertNotNull(carOne.getBrand());
|
||||
Assert.assertNotNull(carTwo.getBrand());
|
||||
Assert.assertNotEquals(carOne.getEngine(), carTwo.getEngine());
|
||||
Assert.assertEquals(carOne.getBrand(), carTwo.getBrand());
|
||||
}
|
||||
|
||||
}
|
||||
7
di-modules/flyway-cdi-extension/README.md
Normal file
7
di-modules/flyway-cdi-extension/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Flyway CDI Extension
|
||||
|
||||
This module contains articles about context and dependency injection (CDI) with Flyway
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [CDI Portable Extension and Flyway](https://www.baeldung.com/cdi-portable-extension)
|
||||
58
di-modules/flyway-cdi-extension/pom.xml
Normal file
58
di-modules/flyway-cdi-extension/pom.xml
Normal file
@@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>flyway-cdi-extension</artifactId>
|
||||
<name>flyway-cdi-extension</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>di-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.enterprise</groupId>
|
||||
<artifactId>cdi-api</artifactId>
|
||||
<version>${cdi-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jboss.weld.se</groupId>
|
||||
<artifactId>weld-se-core</artifactId>
|
||||
<version>${weld-se-core.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>${flyway-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-jdbc</artifactId>
|
||||
<version>${tomcat-jdbc.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>${javax.annotation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cdi-api.version>2.0.SP1</cdi-api.version>
|
||||
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
|
||||
<flyway-core.version>5.1.4</flyway-core.version>
|
||||
<tomcat-jdbc.version>8.5.33</tomcat-jdbc.version>
|
||||
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.cdi.extension;
|
||||
|
||||
import org.apache.tomcat.jdbc.pool.DataSource;
|
||||
import org.flywaydb.core.Flyway;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.enterprise.inject.Any;
|
||||
import javax.enterprise.inject.Default;
|
||||
import javax.enterprise.inject.literal.InjectLiteral;
|
||||
import javax.enterprise.inject.spi.*;
|
||||
import javax.enterprise.util.AnnotationLiteral;
|
||||
|
||||
|
||||
/**
|
||||
* Flyway is now under CDI container like:
|
||||
*
|
||||
* @ApplicationScoped
|
||||
* @FlywayType public class Flyway{
|
||||
* @Inject setDataSource(DataSource dataSource){
|
||||
* //...
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
public class FlywayExtension implements Extension {
|
||||
|
||||
DataSourceDefinition dataSourceDefinition = null;
|
||||
|
||||
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
|
||||
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
|
||||
}
|
||||
|
||||
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
|
||||
AnnotatedType at = patEvent.getAnnotatedType();
|
||||
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
|
||||
}
|
||||
|
||||
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
|
||||
patEvent.configureAnnotatedType()
|
||||
//Add Scope
|
||||
.add(ApplicationScoped.Literal.INSTANCE)
|
||||
//Add Qualifier
|
||||
.add(new AnnotationLiteral<FlywayType>() {
|
||||
})
|
||||
//Decorate setDataSource(DataSource dataSource){} with @Inject
|
||||
.filterMethods(annotatedMethod -> {
|
||||
return annotatedMethod.getParameters().size() == 1 &&
|
||||
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
|
||||
})
|
||||
.findFirst().get().add(InjectLiteral.INSTANCE);
|
||||
}
|
||||
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
|
||||
abdEvent.addBean()
|
||||
.types(javax.sql.DataSource.class, DataSource.class)
|
||||
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
|
||||
.scope(ApplicationScoped.class)
|
||||
.name(DataSource.class.getName())
|
||||
.beanClass(DataSource.class)
|
||||
.createWith(creationalContext -> {
|
||||
DataSource instance = new DataSource();
|
||||
instance.setUrl(dataSourceDefinition.url());
|
||||
instance.setDriverClassName(dataSourceDefinition.className());
|
||||
return instance;
|
||||
});
|
||||
}
|
||||
|
||||
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
|
||||
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
|
||||
flyway.migrate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.inject.Qualifier;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({FIELD, METHOD, PARAMETER, TYPE})
|
||||
@Qualifier
|
||||
public @interface FlywayType {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.cdi.extension;
|
||||
|
||||
import javax.annotation.sql.DataSourceDefinition;
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import javax.enterprise.inject.se.SeContainer;
|
||||
import javax.enterprise.inject.se.SeContainerInitializer;
|
||||
|
||||
@ApplicationScoped
|
||||
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
|
||||
try (SeContainer container = initializer.initialize()) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<beans version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
||||
@@ -0,0 +1,2 @@
|
||||
com.baeldung.cdi.extension.FlywayExtension
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
create table PERSON (
|
||||
ID int not null,
|
||||
NAME varchar(100) not null
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
insert into PERSON (ID, NAME) values (1, 'Axel');
|
||||
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
|
||||
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
|
||||
8
di-modules/guice/README.md
Normal file
8
di-modules/guice/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
## Google Guice
|
||||
|
||||
This module contains articles about Google Guice
|
||||
|
||||
### Relevant Articles
|
||||
|
||||
- [Guide to Google Guice](https://www.baeldung.com/guice)
|
||||
- [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection)
|
||||
29
di-modules/guice/pom.xml
Normal file
29
di-modules/guice/pom.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.examples.guice</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<name>guice</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>di-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>${guice.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<guice.version>4.1.0</guice.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,32 @@
|
||||
|
||||
package com.baeldung.examples;
|
||||
|
||||
import com.baeldung.examples.guice.Communication;
|
||||
import com.baeldung.examples.guice.binding.AOPModule;
|
||||
import com.baeldung.examples.guice.modules.BasicModule;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class RunGuice {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Injector injector = Guice.createInjector(new BasicModule(), new AOPModule());
|
||||
Communication comms = injector.getInstance(Communication.class);
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
while (true) {
|
||||
String input = scanner.nextLine();
|
||||
if (input.equalsIgnoreCase("q")) {
|
||||
System.exit(0);
|
||||
} else {
|
||||
comms.sendMessage(input);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class Account {
|
||||
|
||||
private String accountNumber;
|
||||
private String type;
|
||||
|
||||
public String getAccountNumber() {
|
||||
return accountNumber;
|
||||
}
|
||||
|
||||
public void setAccountNumber(String accountNumber) {
|
||||
this.accountNumber = accountNumber;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public interface AccountService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class AccountServiceImpl implements AccountService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public interface AudioBookService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class AudioBookServiceImpl implements AudioBookService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public interface AuthorService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class AuthorServiceImpl implements AuthorService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public interface BookService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class BookServiceImpl implements BookService {
|
||||
|
||||
private AuthorService authorService;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public interface PersonDao {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.examples.common;
|
||||
|
||||
public class PersonDaoImpl implements PersonDao {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.name.Named;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class Communication {
|
||||
|
||||
final Date start = new Date();
|
||||
|
||||
@Inject
|
||||
private Logger logger;
|
||||
|
||||
@Inject
|
||||
private DefaultCommunicator communicator;
|
||||
|
||||
public Communication(Boolean keepRecords) {
|
||||
if (keepRecords) {
|
||||
System.out.println("keeping records");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sendMessage(String message) {
|
||||
|
||||
return communicator.sendMessage(message);
|
||||
}
|
||||
|
||||
public DefaultCommunicator getCommunicator() {
|
||||
return this.communicator;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.guice.constant.CommunicationModel;
|
||||
|
||||
public interface CommunicationMode {
|
||||
|
||||
public CommunicationModel getMode();
|
||||
|
||||
public boolean sendMessage(String message);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.guice.marker.Communicator;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.name.Named;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class DefaultCommunicator implements Communicator {
|
||||
|
||||
private CommunicationMode defaultCommsMode;
|
||||
@Inject
|
||||
@Named("SMSComms")
|
||||
CommunicationMode smsCommsMode;
|
||||
@Inject
|
||||
@Named("EmailComms")
|
||||
CommunicationMode emailCommsMode;
|
||||
@Inject
|
||||
@Named("IMComms")
|
||||
CommunicationMode imCommsMode;
|
||||
|
||||
protected DefaultCommunicator(CommunicationMode defaultComms) {
|
||||
this.defaultCommsMode = defaultComms;
|
||||
}
|
||||
|
||||
public DefaultCommunicator() {
|
||||
|
||||
}
|
||||
|
||||
public boolean sendMessage(String message) {
|
||||
boolean sent = false;
|
||||
if (defaultCommsMode != null) {
|
||||
sent = sendMessageByDefault(message);
|
||||
} else {
|
||||
sent = smsCommsMode.sendMessage(message);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
private boolean sendMessageByDefault(String message) {
|
||||
boolean sent = false;
|
||||
if (message != null && !message.trim().equals("")) {
|
||||
return defaultCommsMode.sendMessage(message);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.guice.aop.MessageSentLoggable;
|
||||
import com.baeldung.examples.guice.constant.CommunicationModel;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class EmailCommunicationMode implements CommunicationMode {
|
||||
|
||||
@Override
|
||||
public CommunicationModel getMode() {
|
||||
return CommunicationModel.EMAIL;
|
||||
}
|
||||
|
||||
@Override
|
||||
@MessageSentLoggable
|
||||
public boolean sendMessage(String Message) {
|
||||
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
public class Foo {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
|
||||
public class FooProcessor {
|
||||
|
||||
@Inject
|
||||
private Foo foo;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.common.PersonDao;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
public class GuicePersonService {
|
||||
|
||||
@Inject
|
||||
private PersonDao personDao;
|
||||
|
||||
public PersonDao getPersonDao() {
|
||||
return personDao;
|
||||
}
|
||||
|
||||
public void setPersonDao(PersonDao personDao) {
|
||||
this.personDao = personDao;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.common.AccountService;
|
||||
import com.google.inject.Inject;
|
||||
|
||||
public class GuiceUserService {
|
||||
|
||||
@Inject
|
||||
private AccountService accountService;
|
||||
|
||||
public AccountService getAccountService() {
|
||||
return accountService;
|
||||
}
|
||||
|
||||
public void setAccountService(AccountService accountService) {
|
||||
this.accountService = accountService;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.guice.aop.MessageSentLoggable;
|
||||
import com.baeldung.examples.guice.constant.CommunicationModel;
|
||||
import com.google.inject.Inject;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class IMCommunicationMode implements CommunicationMode {
|
||||
|
||||
@Inject
|
||||
private Logger logger;
|
||||
|
||||
@Override
|
||||
public CommunicationModel getMode() {
|
||||
return CommunicationModel.IM;
|
||||
}
|
||||
|
||||
@Override
|
||||
@MessageSentLoggable
|
||||
public boolean sendMessage(String message) {
|
||||
logger.info("IM Message Sent");
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
package com.baeldung.examples.guice;
|
||||
|
||||
import com.baeldung.examples.guice.aop.MessageSentLoggable;
|
||||
import com.baeldung.examples.guice.constant.CommunicationModel;
|
||||
import com.google.inject.Inject;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class SMSCommunicationMode implements CommunicationMode {
|
||||
|
||||
@Inject
|
||||
private Logger logger;
|
||||
|
||||
@Override
|
||||
public CommunicationModel getMode() {
|
||||
return CommunicationModel.SMS;
|
||||
}
|
||||
|
||||
@Override
|
||||
@MessageSentLoggable
|
||||
public boolean sendMessage(String message) {
|
||||
logger.info("SMS message sent");
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
package com.baeldung.examples.guice.aop;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import java.util.logging.Logger;
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class MessageLogger implements MethodInterceptor {
|
||||
|
||||
@Override
|
||||
public Object invoke(MethodInvocation invocation) throws Throwable {
|
||||
Object[] objectArray = invocation.getArguments();
|
||||
int i = 0;
|
||||
for (Object object : objectArray) {
|
||||
Logger.getAnonymousLogger().info("Sending message: " + object.toString());
|
||||
}
|
||||
return invocation.proceed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
package com.baeldung.examples.guice.aop;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface MessageSentLoggable {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
package com.baeldung.examples.guice.binding;
|
||||
|
||||
import com.baeldung.examples.guice.aop.MessageLogger;
|
||||
import com.baeldung.examples.guice.aop.MessageSentLoggable;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.matcher.Matchers;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class AOPModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bindInterceptor(Matchers.any(),
|
||||
Matchers.annotatedWith(MessageSentLoggable.class),
|
||||
new MessageLogger()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
|
||||
package com.baeldung.examples.guice.binding;
|
||||
|
||||
import com.baeldung.examples.guice.Communication;
|
||||
import com.baeldung.examples.guice.CommunicationMode;
|
||||
import com.baeldung.examples.guice.DefaultCommunicator;
|
||||
import com.baeldung.examples.guice.EmailCommunicationMode;
|
||||
import com.baeldung.examples.guice.IMCommunicationMode;
|
||||
import com.baeldung.examples.guice.SMSCommunicationMode;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.name.Names;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class BasicModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
try {
|
||||
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.TYPE));
|
||||
} catch (NoSuchMethodException ex) {
|
||||
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
|
||||
} catch (SecurityException ex) {
|
||||
Logger.getLogger(BasicModule.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
|
||||
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
package com.baeldung.examples.guice.constant;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public enum CommunicationModel {
|
||||
|
||||
EMAIL("Email"), SMS("SMS"), IM("IM"), PHONE("Phone");
|
||||
|
||||
final String name;
|
||||
|
||||
CommunicationModel(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.examples.guice.marker;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Tayo
|
||||
*/
|
||||
public interface Communicator {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
|
||||
package com.baeldung.examples.guice.modules;
|
||||
|
||||
import com.baeldung.examples.guice.Communication;
|
||||
import com.baeldung.examples.guice.CommunicationMode;
|
||||
import com.baeldung.examples.guice.DefaultCommunicator;
|
||||
import com.baeldung.examples.guice.EmailCommunicationMode;
|
||||
import com.baeldung.examples.guice.IMCommunicationMode;
|
||||
import com.baeldung.examples.guice.SMSCommunicationMode;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.name.Names;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class BasicModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
try {
|
||||
bind(Communication.class).toConstructor(Communication.class.getConstructor(Boolean.class));
|
||||
bind(Boolean.class).toInstance(true);
|
||||
} catch (NoSuchMethodException ex) {
|
||||
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
|
||||
} catch (SecurityException ex) {
|
||||
Logger.getLogger(com.baeldung.examples.guice.binding.BasicModule.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
bind(DefaultCommunicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(DefaultCommunicator.class).asEagerSingleton();
|
||||
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("IMComms")).to(IMCommunicationMode.class);
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("EmailComms")).to(EmailCommunicationMode.class);
|
||||
bind(CommunicationMode.class).annotatedWith(Names.named("SMSComms")).to(SMSCommunicationMode.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.examples.guice.modules;
|
||||
|
||||
import com.baeldung.examples.common.AccountService;
|
||||
import com.baeldung.examples.common.AccountServiceImpl;
|
||||
import com.baeldung.examples.common.BookService;
|
||||
import com.baeldung.examples.common.BookServiceImpl;
|
||||
import com.baeldung.examples.common.PersonDao;
|
||||
import com.baeldung.examples.common.PersonDaoImpl;
|
||||
import com.baeldung.examples.guice.Foo;
|
||||
import com.baeldung.examples.guice.Person;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Provider;
|
||||
import com.google.inject.Provides;
|
||||
|
||||
public class GuiceModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
try {
|
||||
bind(AccountService.class).to(AccountServiceImpl.class);
|
||||
bind(Person.class).toConstructor(Person.class.getConstructor());
|
||||
// bind(Person.class).toProvider(new Provider<Person>() {
|
||||
// public Person get() {
|
||||
// Person p = new Person();
|
||||
// return p;
|
||||
// }
|
||||
// });
|
||||
bind(Foo.class).toProvider(new Provider<Foo>() {
|
||||
public Foo get() {
|
||||
return new Foo();
|
||||
}
|
||||
});
|
||||
bind(PersonDao.class).to(PersonDaoImpl.class);
|
||||
|
||||
} catch (NoSuchMethodException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (SecurityException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Provides
|
||||
public BookService bookServiceGenerator() {
|
||||
return new BookServiceImpl();
|
||||
}
|
||||
|
||||
}
|
||||
13
di-modules/guice/src/main/resources/logback.xml
Normal file
13
di-modules/guice/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.examples;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.examples.common.BookService;
|
||||
import com.baeldung.examples.guice.FooProcessor;
|
||||
import com.baeldung.examples.guice.GuicePersonService;
|
||||
import com.baeldung.examples.guice.GuiceUserService;
|
||||
import com.baeldung.examples.guice.Person;
|
||||
import com.baeldung.examples.guice.modules.GuiceModule;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
|
||||
public class GuiceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAccountServiceInjectedInGuiceUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
GuiceUserService guiceUserService = injector.getInstance(GuiceUserService.class);
|
||||
assertNotNull(guiceUserService.getAccountService());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBookServiceIsRegisteredInModule_WhenBookServiceIsInjected_ThenReturnValueIsNotNull() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
BookService bookService = injector.getInstance(BookService.class);
|
||||
assertNotNull(bookService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleBindingsForPerson_WhenPersonIsInjected_ThenTestFailsByProvisionException() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
Person person = injector.getInstance(Person.class);
|
||||
assertNotNull(person);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooInjectedToFooProcessorAsOptionalDependency_WhenFooProcessorIsRetrievedFromContext_ThenCreationExceptionIsNotThrown() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
FooProcessor fooProcessor = injector.getInstance(FooProcessor.class);
|
||||
assertNotNull(fooProcessor);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuicePersonServiceConstructorAnnotatedByInject_WhenGuicePersonServiceIsInjected_ThenInstanceWillBeCreatedFromTheConstructor() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
GuicePersonService personService = injector.getInstance(GuicePersonService.class);
|
||||
assertNotNull(personService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPersonDaoInjectedToGuicePersonServiceBySetterInjection_WhenGuicePersonServiceIsInjected_ThenPersonDaoInitializedByTheSetter() {
|
||||
Injector injector = Guice.createInjector(new GuiceModule());
|
||||
GuicePersonService personService = injector.getInstance(GuicePersonService.class);
|
||||
assertNotNull(personService);
|
||||
assertNotNull(personService.getPersonDao());
|
||||
}
|
||||
|
||||
}
|
||||
22
di-modules/pom.xml
Normal file
22
di-modules/pom.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>di-modules</artifactId>
|
||||
<name>di-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>cdi</module>
|
||||
<module>dagger</module>
|
||||
<module>flyway-cdi-extension</module>
|
||||
<module>guice</module>
|
||||
</modules>
|
||||
</project>
|
||||
Reference in New Issue
Block a user