Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created March 25, 2017 04:52
Show Gist options
  • Save kencoba/48093fb2869c9eba0f49cd6d4dff432b to your computer and use it in GitHub Desktop.
Save kencoba/48093fb2869c9eba0f49cd6d4dff432b to your computer and use it in GitHub Desktop.
LocalDate injection with Producer method. this is useful for unit test.
package producer;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
/**
reference : p.96,"パーフェクトJavaEE"
*/
@ApplicationScoped
public class ConfigProducer {
private Properties props;
@PostConstruct
public void init() {
try (BufferedInputStream bis =
new BufferedInputStream(
this.getClass().getClassLoader().getResourceAsStream("config.properties"))) {
this.props = new Properties();
this.props.load(bis);
} catch (IOException e) {
System.err.println(e);
}
}
@Produces
@Config
public LocalDate getLocalDateConfig(InjectionPoint ip) {
String key = ip.getAnnotated().getAnnotation(Config.class).value();
String value = props.getProperty(key);
if (value.equals("now")) {
return LocalDate.now();
} else {
return LocalDate.parse(value,DateTimeFormatter.ofPattern("yyyy-LLLL-dd"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment