Created
March 25, 2017 04:52
-
-
Save kencoba/48093fb2869c9eba0f49cd6d4dff432b to your computer and use it in GitHub Desktop.
LocalDate injection with Producer method. this is useful for unit test.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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